uadmin

package module
v0.1.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2018 License: MIT Imports: 43 Imported by: 0

README

uAdmin the Golang Web Framework

Easy to use, blazing fast and secure.

go report card GoDoc codecov Build Status

Originally open source by IntegrityNet Solutions and Services

For Documentation:

Social Media:

Screenshots

Dashboard Menu

Dashboard  

Log

Log  

Login Form

Login Form  

Features

  • API configuration
  • Authentication and Permissions
  • Clean and sharp UI
  • Dashboard customization
  • Database schema migration
  • Image cropping
  • IP address and port configuration
  • Log feature that keeps track of many things in your app
  • Multilingual translation
  • MySQL Database Support
  • Offers FREE hosting for your app while you are developing by using a single command: uadmin publish
  • Pretty good security features (SSL, 2-Factor Authentication, Password Reset, Hash Salt, Database Encryption)
  • Public access to media
  • Self relation of foreign key/many2many
  • Sending an email from your app by establishing an email configuration
  • Tag support for fields
  • Validation for user input

Minimum requirements

Operating System Architectures Notes
FreeBSD 10.3 or later amd64, 386 Debian GNU/kFreeBSD not supported
Linux 2.6.23 or later with glibc amd64, 386, arm, arm64, s390x, ppc64le CentOS/RHEL 5.x not supported. Install from source for other libc.
macOS 10.10 or later amd64 Use the clang or gcc that comes with Xcode for cgo support.
Windows 7, Server 2008 R2 or later amd64, 386 Use MinGW gcc. No need for cygwin or msys.
  • A C compiler is required only if you plan to use cgo.
  • You only need to install the command line tools for Xcode. If you have already installed Xcode 4.3+, you can install it from the Components tab of the Downloads preferences panel.
Hardware
  • RAM - minimum 256MB
  • CPU - minimum 2GHz
Software
  • Go Version 1.10.3 or later

Installation

$ go get -u github.com/uadmin/uadmin/...

To test if your installation is fine, run the uadmin command line:

$ uadmin
Usage: uadmin COMMAND [-e email] [-d domain]
This tools allows you to publish your project online

Commands:
  publish         This publishes your project online
  prepare         Generates folders and prepares static and templates
  version         Shows the version of uAdmin

Arguments:
  -e, --email     Your email. This is required for you to be able to maintain your project.
  -d, --domain    You can choose your domain name which will customize your URL

Get full documentation online:
https://uadmin.io/docs/

Your First App

Let's build your first app which is a Todo list. First, we will create a folder for your project and prepare it.

$ mkdir -p ~/go/src/github.com/your_name/todo
$ cd ~/go/src/github.com/your_name/todo
$ uadmin prepare
[   OK   ]   Created: /home/abdullah/go/src/github.com/uadmin/todo1/models
[   OK   ]   Created: /home/abdullah/go/src/github.com/uadmin/todo1/api
[   OK   ]   Created: /home/abdullah/go/src/github.com/uadmin/todo1/views
[   OK   ]   Created: /home/abdullah/go/src/github.com/uadmin/todo1/media
[   OK   ]   Created: /home/abdullah/go/src/github.com/uadmin/todo1/static
[   OK   ]   Created: /home/abdullah/go/src/github.com/uadmin/todo1/templates

Now use your code editor to create main.go and put this code inside it.

package main

import (
	"github.com/uadmin/uadmin"
	"time"
)

type Todo struct {
	uadmin.Model
	Name        string
	Description string `uadmin:"html"`
	TargetDate  time.Time
	Progress    int `uadmin:"progress_bar"`
}

func main() {
	uadmin.Register(Todo{})
	uadmin.StartServer()
}

Now to run your code:

$ go build; ./todo
[   OK   ]   Initializing DB: [9/9]
[   OK   ]   Initializing Languages: [185/185]
[  INFO  ]   Auto generated admin user. Username: admin, Password: admin.
[   OK   ]   Server Started: http://0.0.0.0:8080
         ___       __          _
  __  __/   | ____/ /___ ___  (_)___
 / / / / /| |/ __  / __  __ \/ / __ \
/ /_/ / ___ / /_/ / / / / / / / / / /
\__,_/_/  |_\__,_/_/ /_/ /_/_/_/ /_/

Publish your app

To take your app live, it is simple:

$ uadmin publish
Enter your email: me@example.com
Your project will be published to https://my-proj.uadmin.io
Enter the name of your sub-domain (my-proj) [auto]: my-app
Did you change the default port from 8080?
This is the port you have in uadmin.Port = 8080
Enter the port that your server run on [8080]:
[   OK   ]   Compressing [420/420]
[   OK   ]   Your application has been uploaded
[   OK   ]   Application installed succesfully
[   OK   ]   Your Project has been published to https://my-app.uadmin.io/

Quick Reference

Overriding Save Function

func (m *Model)Save(){
	//business logic
	uadmin.Save(m)
}

Validation

func (v Validate) Validate() (ret map[string]string) {
  ret = map[string]string{}
  if v.Name != "test" {
    ret["Name"] = "Error name not found"
  }
  return
}

Documentation

Index

Constants

View Source
const (
	DEBUG   = 0
	WORKING = 1
	INFO    = 2
	OK      = 3
	WARNING = 4
	ERROR   = 5
)

Reporting Levels

View Source
const Version = "0.1.0-rc.1"

Version number as per Semantic Versioning 2.0.0 (semver.org)

Variables

View Source
var BindIP = ""

BindIP is the IP the application listens to

View Source
var CookieTimeout = -1

CookieTimeout is the timeout of a login cookie in seconds

View Source
var CustomTranslation = []string{
	"uadmin/system",
}

CustomTranslation !

View Source
var DebugDB = false

DebugDB prints all SQL statements going to DB

View Source
var EmailFrom string

EmailFrom email from

View Source
var EmailPassword string

EmailPassword !

View Source
var EmailSMTPServer string

EmailSMTPServer !

View Source
var EmailSMTPServerPort int

EmailSMTPServerPort !

View Source
var EmailUsername string

EmailUsername !

View Source
var EncryptKey = []byte{}

EncryptKey is a key for encyption and decryption of data in the DB

View Source
var LogAdd = true

LogAdd adds a log when a record is added

View Source
var LogDelete = true

LogDelete adds a log when a record is deleted

View Source
var LogEdit = true

LogEdit adds a log when a record is edited

View Source
var LogRead = false

LogRead adds a log when a record is read

View Source
var MaxImageHeight = 600

MaxImageHeight !

View Source
var MaxImageWidth = 800

MaxImageWidth !

View Source
var MaxUploadFileSize = int64(25 * 1024 * 1024)

MaxUploadFileSize is the maximum upload file size in bytes

View Source
var OTPAlgorithm = "sha1"

OTPAlgorithm is the hashing algorithm of OTP

View Source
var OTPDigits = 6

OTPDigits is the number of degits for the OTP

View Source
var OTPPeriod = uint(30)

OTPPeriod is the number of seconds for the OTP to change

View Source
var OTPSkew = uint(5)

OTPSkew is the number of minutes to search around the OTP

View Source
var PageLength = 100

PageLength is the list view max number of records

View Source
var Port = 8080

Port is the port used for http or https server

View Source
var PublicMedia = false

PublicMedia allows public access to media handler without authentication

View Source
var ReportTimeStamp = false

ReportTimeStamp set this to true to hav a time stamp in your logs

View Source
var ReportingLevel = DEBUG

ReportingLevel is the standard reporting level

View Source
var RootURL = "/"

RootURL is where the listener is mapped to

View Source
var Salt = ""

Salt is extra salt added to password hashing

View Source
var Schema map[string]ModelSchema

Schema is the gblobal schema of the system

View Source
var SiteName = "uAdmin"

SiteName is the name of the website that shows on title and dashboard

View Source
var Theme = "default"

Theme is the name of the theme used in uAdmin

Functions

func AdminPage

func AdminPage(order string, asc bool, offset int, limit int, a interface{}, query interface{}, args ...interface{}) (err error)

AdminPage !

func All

func All(a interface{}) (err error)

All fetches all object in the database

func ClearDB

func ClearDB()

ClearDB clears the db object

func Count

func Count(a interface{}, query interface{}, args ...interface{}) int

Count return the count of records in a table based on a filter

func Delete

func Delete(a interface{}) (err error)

Delete records from database

func DeleteList

func DeleteList(a interface{}, query interface{}, args ...interface{}) (err error)

DeleteList !

func Filter

func Filter(a interface{}, query interface{}, args ...interface{}) (err error)

Filter fetches records from the database

func FilterBuilder

func FilterBuilder(params map[string]interface{}) (query string, args []interface{})

FilterBuilder chnages a map filter into a query

func GenerateBase32

func GenerateBase32(length int) string

GenerateBase32 generates a base64 string of length length

func GenerateBase64

func GenerateBase64(length int) string

GenerateBase64 generates a base64 string of length length

func Get

func Get(a interface{}, query interface{}, args ...interface{}) (err error)

Get fetches the first record from the database

func GetDB

func GetDB() *gorm.DB

GetDB returns a pointer to the DB

func GetID

func GetID(m reflect.Value) uint

GetID !

func GetString

func GetString(a interface{}) string

GetString returns string representation on an instance of a model

func JSONMarshal

func JSONMarshal(v interface{}, safeEncoding bool) ([]byte, error)

JSONMarshal Generates JSON format from an object

func Logout

func Logout(r *http.Request)

Logout logs out a user

func NewModel

func NewModel(modelName string, pointer bool) (reflect.Value, bool)

NewModel creates a new model from a model name

func NewModelArray

func NewModelArray(modelName string, pointer bool) (reflect.Value, bool)

NewModelArray creates a new model from a model name

func Preload

func Preload(a interface{}, preload ...string) (err error)

Preload !

func Register

func Register(m ...interface{})

Register is used to register models to uadmin

func RegisterInlines

func RegisterInlines(model interface{}, fk map[string]string)

RegisterInlines is a function to register a model as an inline for another model Parameters: ===========

 model (struct instance): Is the model that you want to add inlines to.
 fk (map[interface{}]string): This is a map of the inlines to be added to the model.
                              The map's key is the name of the model of the inline
                              and the value of the map is the foreign key field's name.
Example:
========
type Person struct {
  uadmin.Model
  Name string
}

type Card struct {
  uadmin.Model
  PersonID uint
  Person   Person
}
func main() {
  ...
  uadmin.RegisterInlines(Person{}, map[string]string{
    "Card": "PersonID",
  })
  ...
}

func ReturnJSON

func ReturnJSON(w http.ResponseWriter, r *http.Request, v interface{})

ReturnJSON returns json to the client

func Save

func Save(a interface{}) (err error)

Save saves the object in the database

func SendEmail

func SendEmail(to, cc, bcc []string, subject, body string) (err error)

SendEmail sends email using system configured variables

func StartSecureServer

func StartSecureServer(certFile, keyFile string)

StartSecureServer !

func StartServer

func StartServer()

StartServer !

func Tf

func Tf(path string, lang string, term string, args ...interface{}) string

Tf is a function for translating strings into any given language Parameters: ===========

path (string): This is where to get the translation from. It is in the
               format of "GROUPNAME/FILENAME" for example: "uadmin/system"
lang (string): Is the language code. If empty string is passed we will use
               the default language.
term (string): The term to translate.
args (...interface{}): Is a list of args to fill the term with place holders

func Trail

func Trail(level int, msg interface{}, i ...interface{})

Trail prints to the log

func Translate

func Translate(raw string, lang string, args ...bool) string

Translate is used to get a translation from a multilingual fields

func Update

func Update(a interface{}, fieldName string, value interface{}, query string, args ...interface{}) (err error)

Update !

func UploadImageHandler

func UploadImageHandler(w http.ResponseWriter, r *http.Request, session *Session)

UploadImageHandler handles files sent from Tiny MCE's photo uploader

Types

type Action

type Action int

Action !

func (Action) Added

func (a Action) Added() Action

Added @

func (Action) Custom

func (a Action) Custom() Action

Custom !

func (Action) Deleted

func (a Action) Deleted() Action

Deleted !

func (Action) LoginDenied

func (a Action) LoginDenied() Action

LoginDenied !

func (Action) LoginSuccessful

func (a Action) LoginSuccessful() Action

LoginSuccessful !

func (Action) Logout

func (a Action) Logout() Action

Logout !

func (Action) Modified

func (a Action) Modified() Action

Modified !

func (Action) PasswordResetDenied

func (a Action) PasswordResetDenied() Action

PasswordResetDenied !

func (Action) PasswordResetRequest

func (a Action) PasswordResetRequest() Action

PasswordResetRequest !

func (Action) PasswordResetSuccessful

func (a Action) PasswordResetSuccessful() Action

PasswordResetSuccessful !

func (Action) Read

func (a Action) Read() Action

type Choice

type Choice struct {
	V        string
	K        uint
	Selected bool
}

Choice is a struct for list choices

type DBSettings

type DBSettings struct {
	Type     string // SQLLite, MySQL
	Name     string // File/DB name
	User     string
	Password string
	Host     string
	Port     int
}

DBSettings !

var Database *DBSettings

Database is the active Database settings

type DashboardMenu

type DashboardMenu struct {
	Model
	MenuName string `uadmin:"required;list_exclude;multilingual;filter"`
	URL      string `uadmin:"required"`
	ToolTip  string
	Icon     string `uadmin:"image"`
	Cat      string `uadmin:"filter"`
	Hidden   bool   `uadmin:"filter"`
}

DashboardMenu !

func (DashboardMenu) String

func (m DashboardMenu) String() string

type F

type F struct {
	Name              string
	DisplayName       string
	Type              string
	TypeName          string
	Value             interface{}
	Help              string
	Max               interface{}
	Min               interface{}
	Format            string
	DefaultValue      string
	Required          bool
	Pattern           string
	PatternMsg        string
	Hidden            bool
	ReadOnly          string
	Searchable        bool
	Filter            bool
	ListDisplay       bool
	FormDisplay       bool
	CategoricalFilter bool
	Translations      []translation
	Choices           []Choice
	IsMethod          bool
	ErrMsg            string
	ProgressBar       map[float64]string
	LimitChoicesTo    func(interface{}, *User) []Choice
	UploadTo          string
	Encrypt           bool
}

F is a field

type GroupPermission

type GroupPermission struct {
	Model
	DashboardMenu   DashboardMenu `uadmin:"required;filter"`
	DashboardMenuID uint
	UserGroup       UserGroup `uadmin:"required;filter"`
	UserGroupID     uint
	Read            bool
	Add             bool
	Edit            bool
	Delete          bool
}

GroupPermission !

func (GroupPermission) HideInDashboard

func (GroupPermission) HideInDashboard() bool

HideInDashboard to return false and auto hide this from dashboard

func (GroupPermission) String

func (g GroupPermission) String() string

type HideInDashboarder

type HideInDashboarder interface {
	HideInDashboard() bool
}

HideInDashboarder used to check if a model should be hidden in dashboard

type Language

type Language struct {
	Model
	EnglishName    string `uadmin:"required;read_only;filter;search"`
	Name           string `uadmin:"required;read_only;filter;search"`
	Flag           string `uadmin:"image;list_exclude"`
	Code           string `uadmin:"filter;read_only;list_exclude"`
	RTL            bool   `uadmin:"list_exclude"`
	Default        bool   `uadmin:"help:Set as the default language;list_exclude"`
	Active         bool   `uadmin:"help:To show this in available languages;filter"`
	AvailableInGui bool   `uadmin:"help:The App is available in this language;read_only"`
}

Language !

func (*Language) Save

func (l *Language) Save()

Save !

func (Language) String

func (l Language) String() string

String !

type Log

type Log struct {
	Model
	Username  string    `uadmin:"filter;read_only"`
	Action    Action    `uadmin:"filter;read_only"`
	TableName string    `uadmin:"filter;read_only"`
	TableID   int       `uadmin:"filter;read_only"`
	Activity  string    `uadmin:"code;read_only" gorm:"type:longtext"`
	RollBack  string    `uadmin:"link;"`
	CreatedAt time.Time `uadmin:"filter;read_only"`
}

Log !

func (*Log) ParseRecord

func (l *Log) ParseRecord(a reflect.Value, modelName string, ID uint, user *User, action Action, r *http.Request) (err error)

ParseRecord !

func (*Log) PasswordReset

func (l *Log) PasswordReset(user string, action Action, r *http.Request) (err error)

PasswordReset !

func (*Log) Save

func (l *Log) Save()

Save !

func (*Log) SignIn

func (l *Log) SignIn(user string, action Action, r *http.Request) (err error)

SignIn !

func (Log) String

func (l Log) String() string

type Model

type Model struct {
	ID        uint       `gorm:"primary_key"`
	DeletedAt *time.Time `sql:"index"`
}

Model is the standard struct to be embedded in any other struct to make it a model for uadmin

type ModelSchema

type ModelSchema struct {
	Name          string // Name of the Model
	DisplayName   string // Display Name of the model
	ModelName     string // URL
	ModelID       uint
	Inlines       []*ModelSchema
	InlinesData   []listData
	Fields        []F
	IncludeFormJS []string
	IncludeListJS []string
	FormModifier  func(*ModelSchema, interface{}, *User)
	ListModifier  func(*ModelSchema, *User) (string, []interface{})
}

ModelSchema for a form

func (ModelSchema) FieldByName

func (s ModelSchema) FieldByName(a string) *F

FieldByName returns a field from a ModelSchema by name or nil if it doen't exist

type Session

type Session struct {
	Model
	Key        string
	User       User `uadmin:"filter"`
	UserID     uint
	LoginTime  time.Time
	LastLogin  time.Time
	Active     bool   `uadmin:"filter"`
	IP         string `uadmin:"filter"`
	PendingOTP bool   `uadmin:"filter"`
	ExpiresOn  *time.Time
}

Session !

func IsAuthenticated

func IsAuthenticated(r *http.Request) *Session

IsAuthenticated returns if the http.Request is authenticated or not

func (*Session) GenerateKey

func (s *Session) GenerateKey()

GenerateKey !

func (Session) HideInDashboard

func (Session) HideInDashboard() bool

HideInDashboard to return false and auto hide this from dashboard

func (*Session) Logout

func (s *Session) Logout()

Logout deactivates a session

func (*Session) Save

func (s *Session) Save()

Save !

func (Session) String

func (s Session) String() string

String return string

type User

type User struct {
	Model
	Username     string    `uadmin:"required;filter"`
	FirstName    string    `uadmin:"filter"`
	LastName     string    `uadmin:"filter"`
	Password     string    `uadmin:"required;password;help:To reset password, clear the field and type a new password.;list_exclude"`
	Email        string    `uadmin:"email"`
	Active       bool      `uadmin:"filter"`
	Admin        bool      `uadmin:"filter"`
	RemoteAccess bool      `uadmin:"filter"`
	UserGroup    UserGroup `uadmin:"filter"`
	UserGroupID  uint
	Photo        string `uadmin:"image"`
	//Language     []Language `gorm:"many2many:user_languages" listExclude:"true"`
	LastLogin   *time.Time `uadmin:"read_only"`
	ExpiresOn   *time.Time
	OTPRequired bool
	OTPSeed     string `uadmin:"list_exclude;hidden;read_only"`
}

User !

func GetUserFromRequest

func GetUserFromRequest(r *http.Request) *User

GetUserFromRequest returns a user from a request

func Login

func Login(r *http.Request, username string, password string) (*User, bool)

Login return *User and a bool for Is OTP Required

func Login2FA

func Login2FA(r *http.Request, username string, password string, otpPass string) *User

Login2FA login using username, password and otp for users with OTPRequired = true

func (*User) GetActiveSession

func (u *User) GetActiveSession() *Session

GetActiveSession !

func (*User) GetDashboardMenu

func (u *User) GetDashboardMenu() (menus []DashboardMenu)

GetDashboardMenu !

func (*User) GetOTP

func (u *User) GetOTP() string

GetOTP !

func (*User) HasAccess

func (u *User) HasAccess(modelName string) UserPermission

HasAccess !

func (*User) Login

func (u *User) Login(pass string, otp string) *Session

Login Logs in user using password and otp. If there is no OTP, just pass an empty string

func (*User) Save

func (u *User) Save()

Save !

func (User) String

func (u User) String() string

String return string

func (User) Validate

func (u User) Validate() (ret map[string]string)

Validate user when saving from uadmin

func (*User) VerifyOTP

func (u *User) VerifyOTP(pass string) bool

VerifyOTP !

type UserGroup

type UserGroup struct {
	Model
	GroupName string `uadmin:"filter"`
}

UserGroup !

func (*UserGroup) HasAccess

func (u *UserGroup) HasAccess(modelName string) GroupPermission

HasAccess !

func (UserGroup) String

func (u UserGroup) String() string

type UserPermission

type UserPermission struct {
	Model
	DashboardMenu   DashboardMenu `gorm:"ForeignKey:DashboardMenuID" required:"true" filter:"true" uadmin:"filter"`
	DashboardMenuID uint          `fk:"true" displayName:"DashboardMenu"`
	User            User          `gorm:"ForeignKey:UserID" required:"true" filter:"true" uadmin:"filter"`
	UserID          uint          `fk:"true" displayName:"User"`
	Read            bool          `uadmin:"filter"`
	Add             bool          `uadmin:"filter"`
	Edit            bool          `uadmin:"filter"`
	Delete          bool          `uadmin:"filter"`
}

UserPermission !

func (UserPermission) HideInDashboard

func (UserPermission) HideInDashboard() bool

HideInDashboard to return false and auto hide this from dashboard

func (UserPermission) String

func (u UserPermission) String() string

Directories

Path Synopsis
cmd
uadmin
The MIT License (MIT) Copyright (c) 2018 otiai10 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The MIT License (MIT) Copyright (c) 2018 otiai10 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
docs
Package helper is a micro package with helper functions for uAdmin
Package helper is a micro package with helper functions for uAdmin

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL