uadmin

package module
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2023 License: MIT Imports: 66 Imported by: 0

README

uAdmin the Golang Web Framework

Easy to use, blazing fast and secure.

go report card GoDoc codecov

Originally open source by IntegrityNet Solutions and Services

For Documentation:

join gophers.slack.com

Social Media:

Screenshots

Dashboard Menu

Dashboard  

Log

Log  

Login Form

Login Form  

Features

  • AB Testing System
  • API Configuration
  • Approval System
  • Authentication and Permissions
  • Clean and sharp UI
  • Dashboard customization
  • Data Access API (dAPI)
  • Database schema migration
  • Error Handling
  • Export to Excel
  • Form and List customization
  • Image Cropping
  • IP address and port configuration
  • Log feature that keeps track of many things in your app
  • Metric System
  • 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
  • System settings could be used system-wide to keep application settings
  • Tag support for fields
  • Translation files preloading
  • Validation for user input
  • Webcam support on image and file fields

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.16 or later

Installation

go get -u github.com/PesTospertnyj/uadmin/
go install github.com/PesTospertnyj/uadmin/cmd/uadmin@latest

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

$ uadmin
Usage: uadmin COMMAND [--src]
This tools helps you prepare a folder for a new project or update static files and templates

Commands:
  prepare         Generates folders and prepares static and templates
  version         Shows the version of uAdmin

Arguments:
  --src           If you want to copy static files and templates from src folder

Get full documentation online:
https://uadmin-docs.readthedocs.io/en/latest/

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: /Users/abdullah/go/src/github.com/twistedhardware/test/models
[   OK   ]   Created: /Users/abdullah/go/src/github.com/twistedhardware/test/api
[   OK   ]   Created: /Users/abdullah/go/src/github.com/twistedhardware/test/views
[   OK   ]   Created: /Users/abdullah/go/src/github.com/twistedhardware/test/media
[  INFO  ]   Copying static/templates from: /Users/abdullah/go/pkg/mod/github.com/PesTospertnyj/uadmin@v0.6.0
[   OK   ]   Created: /Users/abdullah/go/src/github.com/twistedhardware/test/static
[   OK   ]   Created: /Users/abdullah/go/src/github.com/twistedhardware/test/templates

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

package main

import (
	"github.com/PesTospertnyj/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()
}

Prepare modules

$ go mod init
go: creating new go.mod: module github.com/twistedhardware/test
go: to add module requirements and sums:
	go mod tidy

$ go mod tidy
go: finding module for package github.com/PesTospertnyj/uadmin
go: found github.com/PesTospertnyj/uadmin in github.com/PesTospertnyj/uadmin v0.6.0

Run your app (Linux, Apple macOS or Windows):

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

In Windows:

> go build && todo.exe
[   OK   ]   Initializing DB: [14/14]
[   OK   ]   Initializing Languages: [185/185]
[  INFO  ]   Auto generated admin user. Username:admin, Password:admin.
[   OK   ]   Synching System Settings: [49/49]
[   OK   ]   Server Started: http://0.0.0.0:8080
         ___       __          _
  __  __/   | ____/ /___ ___  (_)___
 / / / / /| |/ __  / __  __ \/ / __ \
/ /_/ / ___ / /_/ / / / / / / / / / /
\__,_/_/  |_\__,_/_/ /_/ /_/_/_/ /_/

Quick Reference

Overriding Save Function

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

Validation

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

Documentation

Index

Constants

View Source
const (
	NONE      = 10
	DEBUG     = 0
	WORKING   = 1
	INFO      = 2
	OK        = 3
	WARNING   = 4
	ERROR     = 5
	CRITICAL  = 6
	ALERT     = 7
	EMERGENCY = 8
)

Reporting Levels

View Source
const Version = "0.9.2"

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

View Source
const VersionCodeName = "Gnat"

VersionCodeName is the cool name we give to versions with significant changes. This name should always be a bug's name starting from A-Z them revolving back. This started at version 0.5.0 (Atlas Moth) 0.6.0 Beetle 0.7.0 Catterpiller 0.8.0 Dragonfly 0.9.0 Gnat

Variables

View Source
var APIDisabledAdd = false

APIDisabledAdd controls the data API's disabled for add commands.

View Source
var APIDisabledDelete = false

APIDisabledDelete controls the data API's disabled for delete commands.

View Source
var APIDisabledEdit = false

APIDisabledEdit controls the data API's disabled for edit commands.

View Source
var APIDisabledRead = false

APIDisabledRead controls the data API’s disabled for add commands.

View Source
var APIDisabledSchema = false

APIDisabledSchema controls the data API's disabled for schema commands.

View Source
var APILogAdd = true

APILogAdd controls the data API's logging for add commands.

View Source
var APILogDelete = true

APILogDelete controls the data API's logging for delete commands.

View Source
var APILogEdit = true

APILogEdit controls the data API's logging for edit commands.

View Source
var APILogRead = false

APILogRead controls the data API's logging for read commands.

View Source
var APILogSchema = true

APILogSchema controls the data API's logging for schema commands.

View Source
var APIPostQueryAdd = false

APIPostQueryAdd controls the data API's post query for add commands.

View Source
var APIPostQueryDelete = false

APIPostQueryDelete controls the data API's post query for delete commands.

View Source
var APIPostQueryEdit = false

APIPostQueryEdit controls the data API's post query for edit commands.

View Source
var APIPostQueryRead = false

APIPostQueryRead controls the data API’s post query for add commands.

View Source
var APIPostQuerySchema = false

APIPostQuerySchema controls the data API's post query for schema commands.

View Source
var APIPreQueryAdd = false

APIPreQueryAdd controls the data API's pre query for add commands.

View Source
var APIPreQueryDelete = false

APIPreQueryDelete controls the data API's pre query for delete commands.

View Source
var APIPreQueryEdit = false

APIPreQueryEdit controls the data API's pre query for edit commands.

View Source
var APIPreQueryRead = false

APIPreQueryRead controls the data API’s pre query for add commands.

View Source
var APIPreQuerySchema = false

APIPreQuerySchema controls the data API's pre query for schema commands.

View Source
var APIPublicAdd = false

APIPublicAdd controls the data API's public for add commands.

View Source
var APIPublicDelete = false

APIPublicDelete controls the data API's public for delete commands.

View Source
var APIPublicEdit = false

APIPublicEdit controls the data API's public for edit commands.

View Source
var APIPublicRead = false

APIPublicRead controls the data API’s public for add commands.

View Source
var APIPublicSchema = false

APIPublicSchema controls the data API's public for schema commands.

View Source
var AcceptedJWTIssuers = []string{}

AcceptedJWTIssuers is a list of accepted JWT issuers. By default the local JWTIssuer is accepted. To accept other issuers, add them to this list

View Source
var AllowDAPISignup = false

AllowDAPISignup allows unauthenticated users to sign up

View Source
var AllowedCORSOrigins []string

AllowedCORSOrigins is a list of allowed CORS origins

View Source
var AllowedHosts = "0.0.0.0,127.0.0.1,localhost,::1"

AllowedHosts is a comma separated list of allowed hosts for the server to work. The default value is only for development. Production domain should be added before deployment

View Source
var AllowedIPs = "*"

AllowedIPs is a list of allowed IPs to access uAdmin interfrace in one of the following formats: - "*" = Allow all - "" = Allow none - "192.168.1.1" Only allow this IP - "192.168.1.0/24" Allow all IPs from 192.168.1.1 to 192.168.1.254 You can also create a list of the above formats using comma to separate them. For example: "192.168.1.1,192.168.1.2,192.168.0.0/24"

View Source
var ApprovalHandleFunc func(*Approval) bool

ApprovalHandleFunc is a function that could be called during the save process of each approval

View Source
var BindIP = ""

BindIP is the IP the application listens to.

View Source
var BlockedIPs = ""

BlockedIPs is a list of blocked IPs from accessing uAdmin interfrace in one of the following formats: - "*" = Block all - "" = Block none - "192.168.1.1" Only block this IP - "192.168.1.0/24" Block all IPs from 192.168.1.1 to 192.168.1.254 You can also create a list of the above formats using comma to separate them. For example: "192.168.1.1,192.168.1.2,192.168.0.0/24"

View Source
var CachePermissions = true

CachePermissions allows uAdmin to store permissions data in memory

View Source
var CacheSessions = true

CacheSessions allows uAdmin to store sessions data in memory

View Source
var CacheTranslation = false

CacheTranslation allows a translation to store data in a cache memory.

View Source
var CookieTimeout = -1

CookieTimeout is the timeout of a login cookie in seconds. If the value is -1, then the session cookie will not have an expiry date.

View Source
var CustomDAPIHeaders = map[string]string{}

CustomDAPIHeaders are extra handlers that would be added to dAPI responses

View Source
var CustomDAPILoginHandler func(*http.Request, *User, map[string]interface{}) map[string]interface{}

CustomDAPILoginHandler is a function that can provide extra information in the login return

View Source
var CustomEmailHandler func(to, cc, bcc *[]string, subject, body *string, attachments ...*string) (bool, error)

CustomEmailHandler allows to customize or even override the default email sending method. The return of of the function is a boolean and an error. All parameters are of pointers to allow customization of the parameters that will be passed to the default email sender.

  • The boolean will determine whether to proceed or not. If true, the process will proceed with the default method of sending the email
  • The error will be reported to Trail as type uadmin.ERROR
View Source
var CustomJWT func(r *http.Request, s *Session, payload map[string]interface{}) map[string]interface{}
View Source
var CustomOpenAPI func(*openapi.Schema)

CustomOpenAPI is a handler to be called to customize OpenAPI schema Use of OpenAPI schema generation is under development and should not be used in production

View Source
var CustomOpenAPIJSON func([]byte) []byte

CustomOpenAPIJSON is a handler to be called to customize OpenAPI schema JSON output Use of OpenAPI schema generation is under development and should not be used in production

View Source
var CustomResetPasswordLink = ""

CustomResetPasswordLink is the link sent to the user's email to reset their password the string may include the following place holder: "{SCHEMA}://{HOST}/resetpassword?u={USER_ID}&key={OTP}"

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

CustomTranslation is where you can register custom translation files. To register a custom translation file, always assign it with it's key in the this format "category/name". For example:

uadmin.CustomTranslation = append(uadmin.CustomTranslation, "ui/billing")

This will register the file and you will be able to use it if `uadmin.Tf`. By default there is only one registered custom translation which is "uadmin/system".

View Source
var CustomizeJSON func(http.ResponseWriter, *http.Request, interface{}, []byte) []byte

CustomizeJSON is a function to allow customization of JSON returns

View Source
var DAPISignupActive = true

DAPISignupActive controls if new signed up users are activate automatically

View Source
var DAPISignupAllowRemote = true

DAPISignupAllowRemote controls if new signed up users are can login over the internet

View Source
var DAPISignupGroupID = 0

DAPISignupGroupID is the default user group id new users get when they sign up to leave new signed up users without a group, use value 0 for this variable

View Source
var DebugDB = false

DebugDB prints all SQL statements going to DB.

View Source
var DefaultMediaPermission = os.FileMode(0644)

DefaultMediaPermission is the default permission applied to to files uploaded to the system

View Source
var DisableAdminUI = false

DisableAdminUI disables access to the UI and all related APIs

View Source
var DisableDAPIAuth = true

DisableDAPIAuth enables or disables access to dAPI auth API

View Source
var EmailFrom string

EmailFrom identifies where the email is coming from.

View Source
var EmailPassword string

EmailPassword sets the password of an email.

View Source
var EmailSMTPServer string

EmailSMTPServer sets the name of the SMTP Server in an email.

View Source
var EmailSMTPServerPort int

EmailSMTPServerPort sets the port number of an SMTP Server in an email.

View Source
var EmailUsername string

EmailUsername sets the username of an email.

View Source
var EnableDAPICORS bool

EnableDAPICORS controller whether dAPI is uses CORS protocol to allow cross-origan requests

View Source
var EncryptKey = []byte{}

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

View Source
var ErrorHandleFunc func(int, string, string)

ErrorHandleFunc is a function that will be called everytime Trail is called. It receives one parameter for error level, one for error message and one for runtime stack trace

View Source
var FavIcon = "/static/uadmin/favicon.ico"

FavIcon is the fav icon that shows on uAdmin UI

View Source
var HTTPLogFormat = "%a %>s %B %U %D"

HTTPLogFormat is the format used to log HTTP access %a: Client IP address %A: Server hostname/IP %{local}p: Server port %U: Path %c: All cookies %{NAME}c: Cookie named 'NAME' %{GET}f: GET request parameters %{POST}f: POST request parameters %B: Response length %>s: Response code %D: Time taken in microseconds %T: Time taken in seconds %I: Request length

View Source
var JWT = ""

JWT secret for signing tokens

View Source
var JWTIssuer = ""

jwtIssuer is a URL to identify the application issuing JWT tokens. If left empty, a partial hash of JWT will be assigned. This is also used to identify the as JWT audience.

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 LogHTTPRequests = true

LogHTTPRequests logs http requests to syslog

View Source
var LogRead = false

LogRead adds a log when a record is read.

View Source
var LogTrail = false

LogTrail stores Trail logs to syslog

View Source

Logo is the main logo that shows on uAdmin UI

View Source
var MaxImageHeight = 600

MaxImageHeight sets the maximum height of an image.

View Source
var MaxImageWidth = 800

MaxImageWidth sets the maximum width of an image.

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 digits 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 OptimizeSQLQuery = false

OptimizeSQLQuery selects columns during rendering a form a list to visible fields. This means during the filtering of a form the select statement will not include any field with `hidden` tag. For list it will not select any field with `list_exclude`

View Source
var PageLength = 100

PageLength is the list view max number of records.

View Source
var PasswordAttempts = 5

PasswordAttempts is the maximum number of invalid password attempts before the IP address is blocked for some time from using the system

View Source
var PasswordTimeout = 15

PasswordTimeout is the amount of time in minutes the IP will be blocked for after reaching the the maximum invalid password attempts

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 RateLimit int64 = 3

RateLimit is the maximum number of requests/second for any unique IP

View Source
var RateLimitBurst int64 = 3

RateLimitBurst is the maximum number of requests for an idle user

View Source
var ReportTimeStamp = false

ReportTimeStamp set this to true to have a time stamp in your logs.

View Source
var ReportingLevel = DEBUG

ReportingLevel is the standard reporting level.

View Source
var ResetPasswordMessage = `` /* 329-byte string literal not displayed */

ResetPasswordMessage is a message that can be sent to the user email when a password reset request sends an email. This message may include the following place holders: {NAME}: user real name {WEBSITE}: website name {URL}: link to the password reset page

View Source
var RestrictSessionIP = false

RestrictSessionIP is to block access of a user if their IP changes from their original IP during login

View Source
var RetainMediaVersions = true

RetainMediaVersions is to allow the system to keep files uploaded even after they are changed. This allows the system to "Roll Back" to an older version of the file.

View Source
var RootURL = "/"

RootURL is where the listener is mapped to.

View Source
var Salt = ""

Salt is added to password hashing

View Source
var Schema map[string]ModelSchema

Schema is the global schema of the system.

View Source
var ServerReady = false

ServerReady is a variable that is set to true once the server is ready to use

View Source
var SignupValidationHandler func(user *User) error

SignupValidationHandler can be used to validate or customize new signed up users. Note that the password in the password field is passed in plain text. Do not plain text passwords anywhere.

View Source
var SiteName = "uAdmin"

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

View Source
var SystemMetrics = false

SystemMetrics enables uAdmin system metrics to be recorded

View Source
var Theme = "default"

Theme is the name of the theme used in uAdmin.

View Source
var TimeZone = "local"

TimeZone specifies the the default time zone for the system. Valid values include IANA Time Zones like America/New_York, Asia/Riyadh and UTC. To get local time zone use "local"

View Source
var TrailCacheSize = 65536

TrailCacheSize is the number of bytes to keep in memory of trail logs

View Source
var TrailLoggingLevel = INFO

TrailLoggingLevel is the minimum level to be logged into syslog

View Source
var UserMetrics = false

UserMetrics enables the user metrics to be recorded

Functions

func ABTestClick

func ABTestClick(r *http.Request, group string)

ABTestClick is a function to register a click for an ABTest group

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 Avg

func Avg(a interface{}, column string, query interface{}, args ...interface{}) float64

Avg return the average of a column in a table based on a filter

func AvgTable

func AvgTable(table string, column string, query interface{}, args ...interface{}) float64

AvgTable return the average of a column in a table based on a filter

func CORSHandler

func CORSHandler(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)

func CheckCSRF

func CheckCSRF(r *http.Request) bool

CheckCSRF checks if the request is a possible CSRF. CSRF or Cross-Site Request Forgery is a type of attack here a logged in user clicks on a link that is sent to a website where the user is already authenticated and has instructions for the website to change some state. A possible attack could delete user or system data, change it or add new data to the system. Anti-CSRF measures are implemented in all state chaning APIs and UI handler.

The way uAdmin implements CSRF is by checking for a request parameter GET or POST called `x-csrf-token`. The value of this parameter could be equal to the session key. You can get the session key from the session cookie or if you are using `uadmin.RenderHTML` or `uadmin.RenderHTMLMulti`, then you will find it in the context as `{{CSRF}}`. If you submitting a form you can add this value to a hidden input.

To implement anti CSRF protection in your own API:

func MyAPI(w http.ResponseWriter, r *http.Request) {
	if CheckCSRF(r) {
		uadmin.ReturnJSON(w, r, map[string]interface{}{
			"status": "error",
			"err_msg": "The request does not have x-csrf-token",
		})
	}

	// API code ...
}

http.HandleFunc("/myapi/", MyAPI)

If you you call this API:

http://0.0.0.0:8080/myapi/

It will return an error message and the system will create a CRITICAL level log with details about the possible attack. To make the request work, `x-csrf-token` paramtere should be added.

http://0.0.0.0:8080/myapi/?x-csrf-token=MY_SESSION_KEY

Where you replace `MY_SESSION_KEY` with the session key.

func CheckRateLimit

func CheckRateLimit(r *http.Request) bool

CheckRateLimit checks if the request has remaining quota or not. If it returns false, the IP in the request has exceeded their quota

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 CountTable

func CountTable(table string, query interface{}, args ...interface{}) int

CountTable 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 deletes multiple records from database

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 changes a map filter into a query

func FilterList

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

FilterList fetches the all record from the database matching query and args where it selects only visible fields in the form based on given schema

func FilterSorted

func FilterSorted(order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error)

Filter fetches records from the database

func FilterSortedTable

func FilterSortedTable(table string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error)

Filter fetches records from the database

func FilterSortedValue

func FilterSortedValue(table string, column string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error)

Filter fetches records from the database

func FilterTable

func FilterTable(table string, a interface{}, query interface{}, args ...interface{}) (err error)

Filter fetches records from the database

func GenerateBase32

func GenerateBase32(length int) string

GenerateBase32 generates a base32 string of length length

func GenerateBase64

func GenerateBase64(length int) string

GenerateBase64 generates a base64 string of length length

func GenerateOpenAPISchema

func GenerateOpenAPISchema()

GenerateOpenAPISchema generates API schema for dAPI that is compatible with OpenAPI 3.1.0 Use of OpenAPI schema generation is under development and should not be used in production

func Get

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

Get fetches the first record from the database matching query and args

func GetABTest

func GetABTest(r *http.Request, a interface{}, query interface{}, args ...interface{}) (err error)

GetABTest is like Get function but implements AB testing for the results

func GetDB

func GetDB() *gorm.DB

GetDB returns a pointer to the DB

func GetFieldsAPI

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

GetFieldsAPI returns a list of fields in a model

func GetForm

func GetForm(a interface{}, s *ModelSchema, query interface{}, args ...interface{}) (err error)

GetForm fetches the first record from the database matching query and args where it selects only visible fields in the form based on given schema

func GetHostName

func GetHostName(r *http.Request) string

GetHostName is a function that returns the host name from a request

func GetID

func GetID(m reflect.Value) uint

GetID !

func GetModelsAPI

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

GetModelsAPI returns a list of models

func GetRemoteIP

func GetRemoteIP(r *http.Request) string

GetRemoteIP is a function that returns the IP for a remote user from a request

func GetSchema

func GetSchema(r *http.Request) string

GetSchema is a function that returns the schema for a request (http, https)

func GetSetting

func GetSetting(code string) interface{}

GetSetting return the value of a setting based on its code

func GetSorted

func GetSorted(order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error)

Get fetches the first record from the database matching query and args with sorting

func GetSortedTable

func GetSortedTable(table string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error)

Get fetches the first record from the database matching query and args with sorting

func GetString

func GetString(a interface{}) string

GetString returns string representation on an instance of a model

func GetStringer

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

GetStringer fetches the first record from the database matching query and args and get only fields tagged with `stringer` tag. If no field has `stringer` tag then it gets all the fields

func GetTable

func GetTable(table string, a interface{}, query interface{}, args ...interface{}) (err error)

Get fetches the first record from the database matching query and args with sorting

func GetValueSorted

func GetValueSorted(table string, column string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error)

Get fetches the first record from the database matching query and args with sorting

func Handler

func Handler(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request)

Handler is a function that takes an http handler function and returns an http handler function that has extra functionality including logging

func IncrementMetric

func IncrementMetric(name string)

IncrementMetric increments the value of a

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 Max

func Max(a interface{}, column string, query interface{}, args ...interface{}) float64

Max return the maximum of a column in a table based on a filter

func MaxTable

func MaxTable(table string, column string, query interface{}, args ...interface{}) float64

MaxTable return the maximum of a column in a table based on a filter

func Min

func Min(a interface{}, column string, query interface{}, args ...interface{}) float64

Min return the minimum of a column in a table based on a filter

func MinTable

func MinTable(table string, column string, query interface{}, args ...interface{}) float64

MinTable return the minimum of a column in a table based on a filter

func NewMetric

func NewMetric(name string, template string) error

NewMetric creates a new metric

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 fills the data from foreign keys into structs. You can pass in preload alist of fields to be preloaded. If nothing is passed, every foreign key is preloaded

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 RegisterTrailChan

func RegisterTrailChan(c chan string)

func RenderHTML

func RenderHTML(w http.ResponseWriter, r *http.Request, path string, data interface{}, funcs ...interface{})

RenderHTML creates a new template and applies a parsed template to the specified data object. For function, Tf is available by default and if you want to add functions to your template, just add them to funcs which will add them to the template with their original function names. If you added anonymous functions, they will be available in your templates as func1, func2 ...etc.

func RenderMultiHTML

func RenderMultiHTML(w http.ResponseWriter, r *http.Request, path []string, data interface{}, funcs ...interface{})

RenderMultiHTML creates a new template and applies a parsed template to the specified data object. For function, Tf is available by default and if you want to add functions to your template, just add them to funcs which will add them to the template with their original function names. If you added anonymous functions, they will be available in your templates as func1, func2 ...etc.

func ReturnJSON

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

ReturnJSON returns json to the client

func SQLInjection

func SQLInjection(r *http.Request, key, value string) bool

SQLInjection is the function to check for SQL injection attacks. Parameters:

-key: column_name, table name
-value: WHERE key(OP)value, SET key=value, VALUES (key,key...)

return true for sql injection attempt and false for safe requests

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, attachments ...string) (err error)

SendEmail sends email using system configured variables

func SetMetric

func SetMetric(name string, value float64)

SetMetric sets the value of a gauge metric

func SetSessionCookie

func SetSessionCookie(w http.ResponseWriter, r *http.Request, s *Session) string

SetSessionCookie sets the session cookie value, The the value passed in session is nil, then the session assigned will be a no user session

func StartSecureServer

func StartSecureServer(certFile, keyFile string)

StartSecureServer !

func StartServer

func StartServer()

StartServer !

func StaticHandler

func StaticHandler(w http.ResponseWriter, r *http.Request)

StaticHandler is a function that serves static files

func Std

func Std(a interface{}, column string, query interface{}, args ...interface{}) float64

Std return the standard diviation of a column in a table based on a filter

func StdTable

func StdTable(table string, column string, query interface{}, args ...interface{}) float64

StdTable return the standard diviation of a column in a table based on a filter

func Sum

func Sum(a interface{}, column string, query interface{}, args ...interface{}) float64

Sum return the sum of a column in a table based on a filter

func SumTable

func SumTable(table string, column string, query interface{}, args ...interface{}) float64

SumTable return the sum of a column in a table based on a filter

func Syslogf

func Syslogf(level int, msg string, a ...interface{})

Syslogf records a log in the system in syslog. For Windows it created a file and records the logs there.

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 TimeMetric

func TimeMetric(name string, div float64, f func())

TimeMetric runs a function and times it as a metric

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 TranslateSchema

func TranslateSchema(s *ModelSchema, lang string)

TranslateSchema translate a model schema

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

func ValidateIP

func ValidateIP(r *http.Request, allow string, block string) bool

ValidateIP is a function to check if the IP in the request is allowed in the allowed based on allowed and block strings

Types

type ABTest

type ABTest struct {
	Model
	Name        string     `uadmin:"required"`
	Type        ABTestType `uadmin:"required"`
	StaticPath  string
	ModelName   ModelList
	Field       FieldList
	PrimaryKey  int
	Active      bool
	Group       string
	ResetABTest string `uadmin:"link"`
}

ABTest is a model that stores an A/B test

func (ABTest) Reset

func (a ABTest) Reset()

Reset resets the impressions and clicks to 0 based on a specified AB Test ID

func (*ABTest) Save

func (a *ABTest) Save()

Save an ABTest

type ABTestType

type ABTestType int

ABTestType is the type of the AB testing: model or static

func (ABTestType) Model

func (ABTestType) Model() ABTestType

Model is used to do AB testing for model values coming from database

func (ABTestType) Static

func (ABTestType) Static() ABTestType

Static is used to do AB testing for static assets (images, js, css, ...)

type ABTestValue

type ABTestValue struct {
	Model
	ABTest      ABTest
	ABTestID    uint
	Value       string `uadmin:"list_exclude"`
	Active      bool
	Impressions int
	Clicks      int
}

ABTestValue is a model to represent a possible value of an AB test

func (*ABTestValue) ClickThroughRate

func (a *ABTestValue) ClickThroughRate() float64

ClickThroughRate returns the rate of click through of this value

func (ABTestValue) ClickThroughRate__Form__List

func (a ABTestValue) ClickThroughRate__Form__List() string

ClickThroughRate__Form__List shows the click through rate in form and list views

func (ABTestValue) HideInDashboard

func (ABTestValue) HideInDashboard() bool

HideInDashboard to hide it from dashboard

func (ABTestValue) Preview__Form__List

func (a ABTestValue) Preview__Form__List() string

Preview__Form__List shows a preview of the AB test's value

func (*ABTestValue) String

func (a *ABTestValue) String() string

type APIDisabledAdder

type APIDisabledAdder interface {
	APIDisabledAdd(*http.Request) bool
}

APIDisabledAdder is an interface for models to disable access to add function in dAPI

type APIDisabledDeleter

type APIDisabledDeleter interface {
	APIDisabledDelete(*http.Request) bool
}

APIDisabledDeleter is an interface for models to disable access to delete function in dAPI

type APIDisabledEditor

type APIDisabledEditor interface {
	APIDisabledEdit(*http.Request) bool
}

APIDisabledEditor is an interface for models to disable access to edit function in dAPI

type APIDisabledReader

type APIDisabledReader interface {
	APIDisabledRead(*http.Request) bool
}

APIDisabledReader is an interface for models to disable access to read function in dAPI

type APIDisabledSchemer

type APIDisabledSchemer interface {
	APIDisabledSchema(*http.Request) bool
}

APIDisabledSchemer is an interface for models to disable access to schema function in dAPI

type APILogAdder

type APILogAdder interface {
	APILogAdd(*http.Request) bool
}

APILogAdder is an interface for models to control logging their add function in dAPI

type APILogDeleter

type APILogDeleter interface {
	APILogDelete(*http.Request) bool
}

APILogDeleter is an interface for models to control logging their delete function in dAPI

type APILogEditor

type APILogEditor interface {
	APILogEdit(*http.Request) bool
}

APILogEditor is an interface for models to control logging their edit function in dAPI

type APILogReader

type APILogReader interface {
	APILogRead(*http.Request) bool
}

APILogReader is an interface for models to control logging their read function in dAPI

type APILogSchemer

type APILogSchemer interface {
	APILogSchema(*http.Request) bool
}

APILogSchemer is an interface for models to control logging their schema function in dAPI

type APIPostQueryAdder

type APIPostQueryAdder interface {
	APIPostQueryAdd(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}

APIPostQueryAdder is an interface for models to run after processing add function in dAPI and before returning the results. Returning false stops the rest of the process from happening

type APIPostQueryDeleter

type APIPostQueryDeleter interface {
	APIPostQueryDelete(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}

APIPostQueryDeleter is an interface for models to run after processing delete function in dAPI and before returning the results. Returning false stops the rest of the process from happening

type APIPostQueryEditor

type APIPostQueryEditor interface {
	APIPostQueryEdit(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}

APIPostQueryEditor is an interface for models to run after processing edit function in dAPI and before returning the results. Returning false stops the rest of the process from happening

type APIPostQueryReader

type APIPostQueryReader interface {
	APIPostQueryRead(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}

APIPostQueryReader is an interface for models to run after processing read function in dAPI and before returning the results. Returning false stops the rest of the process from happening

type APIPostQuerySchemer

type APIPostQuerySchemer interface {
	APIPostQuerySchema(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}

APIPostQuerySchemer is an interface for models to run after processing schema function in dAPI and before returning the results. Returning false stops the rest of the process from happening

type APIPreQueryAdder

type APIPreQueryAdder interface {
	APIPreQueryAdd(http.ResponseWriter, *http.Request) bool
}

APIPreQueryAdder is an interface for models to run before processing add function in dAPI. Returning false stops the rest of the process from happening

type APIPreQueryDeleter

type APIPreQueryDeleter interface {
	APIPreQueryDelete(http.ResponseWriter, *http.Request) bool
}

APIPreQueryDeleter is an interface for models to run before processing delete function in dAPI. Returning false stops the rest of the process from happening

type APIPreQueryEditor

type APIPreQueryEditor interface {
	APIPreQueryEdit(http.ResponseWriter, *http.Request) bool
}

APIPreQueryEditor is an interface for models to run before processing edit function in dAPI. Returning false stops the rest of the process from happening

type APIPreQueryReader

type APIPreQueryReader interface {
	APIPreQueryRead(http.ResponseWriter, *http.Request) bool
}

APIPreQueryReader is an interface for models to run before processing read function in dAPI. Returning false stops the rest of the process from happening

type APIPreQuerySchemer

type APIPreQuerySchemer interface {
	APIPreQuerySchema(http.ResponseWriter, *http.Request) bool
}

APIPreQuerySchemer is an interface for models to run before processing schema function in dAPI. Returning false stops the rest of the process from happening

type APIPublicAdder

type APIPublicAdder interface {
	APIPublicAdd(*http.Request) bool
}

APIPublicAdder is an interface for models to control public access to add function in dAPI

type APIPublicDeleter

type APIPublicDeleter interface {
	APIPublicDelete(*http.Request) bool
}

APIPublicDeleter is an interface for models to control public access to delete function in dAPI

type APIPublicEditor

type APIPublicEditor interface {
	APIPublicEdit(*http.Request) bool
}

APIPublicEditor is an interface for models to control public access to read function in dAPI

type APIPublicReader

type APIPublicReader interface {
	APIPublicRead(*http.Request) bool
}

APIPublicReader is an interface for models to control public access to read function in dAPI

type APIPublicSchemer

type APIPublicSchemer interface {
	APIPublicSchema(*http.Request) bool
}

APIPublicSchemer is an interface for models to control public access to schema function in dAPI

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) GetSchema

func (a Action) GetSchema() Action

GetSchema !

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 Approval

type Approval struct {
	Model
	ModelName           string `uadmin:"read_only"`
	ModelPK             uint   `uadmin:"read_only"`
	ColumnName          string `uadmin:"read_only"`
	OldValue            string `uadmin:"read_only"`
	NewValue            string
	NewValueDescription string    `uadmin:"read_only"`
	ChangedBy           string    `uadmin:"read_only"`
	ChangeDate          time.Time `uadmin:"read_only"`
	ApprovalAction      ApprovalAction
	ApprovalBy          string     `uadmin:"read_only"`
	ApprovalDate        *time.Time `uadmin:"read_only"`
	ViewRecord          string     `uadmin:"link"`
	UpdatedBy           string     `uadmin:"read_only;hidden;list_exclude"`
}

Approval is a model that stores approval data

func (*Approval) Save

func (a *Approval) Save()

Save overides save

func (*Approval) String

func (a *Approval) String() string

type ApprovalAction

type ApprovalAction int

ApprovalAction is a selection of approval actions

func (ApprovalAction) Approved

func (ApprovalAction) Approved() ApprovalAction

Approved is an accepted change

func (ApprovalAction) Rejected

func (ApprovalAction) Rejected() ApprovalAction

Rejected is a rejected change

type CKey

type CKey string

CKey is the standard key used in uAdmin for context keys

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 `json:"type"` // sqlite, mysql, postgres
	Name     string `json:"name"` // File/DB name
	User     string `json:"user"`
	Password string `json:"password"`
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Timezone string `json:"timezone"`
}

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) GetImageSize

func (m DashboardMenu) GetImageSize() (int, int)

GetImageSize customizes the icons as 128x128

func (DashboardMenu) String

func (m DashboardMenu) String() string

type DataType

type DataType int

DataType is a list of data types used for settings

func (DataType) Boolean

func (DataType) Boolean() DataType

Boolean is a type

func (DataType) DateTime

func (DataType) DateTime() DataType

DateTime is a type

func (DataType) File

func (DataType) File() DataType

File is a type

func (DataType) Float

func (DataType) Float() DataType

Float is a type

func (DataType) Image

func (DataType) Image() DataType

Image is a type

func (DataType) Integer

func (DataType) Integer() DataType

Integer is a type

func (DataType) String

func (DataType) String() DataType

String is a type

type F

type F struct {
	Name              string
	DisplayName       string
	ColumnName        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                `json:"-"`
	LimitChoicesTo    func(interface{}, *User) []Choice `json:"-"`
	UploadTo          string
	Encrypt           bool
	Approval          bool
	NewValue          interface{}
	OldValue          interface{}
	ChangedBy         string
	ChangeDate        *time.Time
	ApprovalAction    ApprovalAction
	ApprovalDate      *time.Time
	ApprovalBy        string
	ApprovalID        uint
	WebCam            bool
	Stringer          bool
	Deprecated        bool
}

F is a field

func (F) MarshalJSON

func (f F) MarshalJSON() ([]byte, error)

MarshalJSON customizes F json export

type FieldList

type FieldList int

FieldList is a list of fields from schema for a registered model

type FieldType

type FieldType int

FieldType for field type in builder field

func (FieldType) Boolean

func (FieldType) Boolean() FieldType

Boolean for boolean type

func (FieldType) Code

func (FieldType) Code() FieldType

Code for code type

func (FieldType) DateTime

func (FieldType) DateTime() FieldType

DateTime for time.Time type

func (FieldType) DateTimePtr

func (FieldType) DateTimePtr() FieldType

DateTimePtr for time.Time pointer type

func (FieldType) Email

func (FieldType) Email() FieldType

Email for email type

func (FieldType) File

func (FieldType) File() FieldType

File for file type

func (FieldType) Float

func (FieldType) Float() FieldType

Float for float type

func (FieldType) ForeignKey

func (FieldType) ForeignKey() FieldType

ForeignKey for fk type

func (FieldType) HTML

func (FieldType) HTML() FieldType

HTML for html type

func (FieldType) Image

func (FieldType) Image() FieldType

Image for image type

func (FieldType) Int

func (FieldType) Int() FieldType

Int for int type

func (FieldType) Link() FieldType

Link for link type

func (FieldType) M2M

func (FieldType) M2M() FieldType

M2M for m2m type

func (FieldType) Money

func (FieldType) Money() FieldType

Money for money type

func (FieldType) Multilingual

func (FieldType) Multilingual() FieldType

Multilingual for multiminual type

func (FieldType) Password

func (FieldType) Password() FieldType

Password for password type

func (FieldType) ProgressBar

func (FieldType) ProgressBar() FieldType

ProgressBar for progressbar type

func (FieldType) StaticList

func (FieldType) StaticList() FieldType

StaticList for list type

func (FieldType) String

func (FieldType) String() FieldType

String for string type

type GetImageSizer

type GetImageSizer interface {
	GetImageSize() (int, int)
}

GetImageSizer can be inplemented for any model to customize the image size uploaded to that model

type GroupPermission

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

GroupPermission !

func (GroupPermission) HideInDashboard

func (GroupPermission) HideInDashboard() bool

HideInDashboard to return false and auto hide this from dashboard

func (*GroupPermission) Save

func (g *GroupPermission) Save()

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 GetActiveLanguages

func GetActiveLanguages() []Language

GetActiveLanguages returns a list of active langages

func GetDefaultLanguage

func GetDefaultLanguage() Language

GetDefaultLanguage returns the default 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" sql:"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 MinioConfig added in v1.0.2

type MinioConfig struct {
	// contains filtered or unexported fields
}

func NewMinioConfig added in v1.0.2

func NewMinioConfig(endpoint string, accessKeyId string, secretAccessKey string, useSSl bool, bucketName string,
	location string, policy string, isHttps bool) *MinioConfig

type MinioService added in v1.0.2

type MinioService interface {
	UploadFile(ctx context.Context, filename, contentType string, size int64, file io.Reader) (string, error)
}

func NewMinioService added in v1.0.2

func NewMinioService(ctx context.Context, config *MinioConfig) (MinioService, error)

type Model

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

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

type ModelList

type ModelList int

ModelList a list of registered models

type ModelSchema

type ModelSchema struct {
	Name          string // Name of the Model e.g. OrderItem
	DisplayName   string // Display Name of the model e.g. Order Items
	ModelName     string // URL e.g. orderitem
	TableName     string // DB table name e.g. order_items
	Category      string
	ModelID       uint
	Inlines       []*ModelSchema
	InlinesData   []listData
	Fields        []F
	IncludeFormJS []string
	IncludeListJS []string
	FormModifier  func(*ModelSchema, interface{}, *User)            `json:"-"`
	ListModifier  func(*ModelSchema, *User) (string, []interface{}) `json:"-"`
	FormTheme     string
	ListTheme     string
}

ModelSchema for a form

func (ModelSchema) FieldByColumnName

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

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

func (ModelSchema) FieldByName

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

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

func (*ModelSchema) GetFormTheme

func (s *ModelSchema) GetFormTheme() string

GetFormTheme returns the theme for this model or the global theme if there is no assigned theme for the model

func (*ModelSchema) GetListTheme

func (s *ModelSchema) GetListTheme() string

GetListTheme returns the theme for this model or the global theme if there is no assigned theme for the model

func (ModelSchema) MarshalJSON

func (s ModelSchema) MarshalJSON() ([]byte, error)

MarshalJSON customizes json export for models schema

type SchemaCategory

type SchemaCategory interface {
	SchemaCategory() string
}

SchemaCategory provides a default category for the model. This can be customized later from the UI

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 Login

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

Login return *User and a bool for Is OTP Required

func Login2FA

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

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

func Login2FAKey

func Login2FAKey(r *http.Request, key string, otpPass string) *Session

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

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 Setting

type Setting struct {
	Model
	Name         string `uadmin:"required;filter;search"`
	DefaultValue string
	DataType     DataType `uadmin:"required;filter"`
	Value        string
	Help         string          `uadmin:"search" sql:"type:text;"`
	Category     SettingCategory `uadmin:"required;filter"`
	CategoryID   uint
	Code         string `uadmin:"read_only;search"`
}

Setting model stored system settings

func (*Setting) ApplyValue

func (s *Setting) ApplyValue()

ApplyValue changes uAdmin global variables' value based in the setting value

func (*Setting) GetCode

func (s *Setting) GetCode() string

func (*Setting) GetValue

func (s *Setting) GetValue() interface{}

GetValue returns an interface representing the value of the setting

func (*Setting) ParseFormValue

func (s *Setting) ParseFormValue(v []string)

ParseFormValue takes the value of a setting from an HTTP request and saves in the instance of setting

func (*Setting) Save

func (s *Setting) Save()

Save overides save

type SettingCategory

type SettingCategory struct {
	Model
	Name string
	Icon string `uadmin:"image"`
}

SettingCategory is a category for system settings

type User

type User struct {
	Model
	Username     string    `uadmin:"required;filter;search"`
	FirstName    string    `uadmin:"filter;search"`
	LastName     string    `uadmin:"filter;search"`
	Password     string    `uadmin:"required;password;help:To reset password, clear the field and type a new password.;list_exclude"`
	Email        string    `uadmin:"email;search"`
	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"`
	PasswordReset *time.Time
}

User !

func GetUserFromRequest

func GetUserFromRequest(r *http.Request) *User

GetUserFromRequest returns a user from a request

func (u *User) GeneratePasswordResetLink(r *http.Request, link string) (string, error)

func (*User) GeneratePasswordResetOTP

func (u *User) GeneratePasswordResetOTP() string

func (*User) GetAccess

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

GetAccess returns the user's permission to a dashboard menu based on their admin status, group and user permissions

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 returns the user level permission to a model. The modelName the the URL of the model

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 !

func (*User) VerifyOTPAtPasswordReset

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

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 `uadmin:"filter"`
	DashboardMenuID uint          ``
	User            User          `uadmin:"filter"`
	UserID          uint          ``
	Read            bool          `uadmin:"filter"`
	Add             bool          `uadmin:"filter"`
	Edit            bool          `uadmin:"filter"`
	Delete          bool          `uadmin:"filter"`
	Approval        bool          `uadmin:"filter"`
}

UserPermission !

func (UserPermission) HideInDashboard

func (UserPermission) HideInDashboard() bool

HideInDashboard to return false and auto hide this from dashboard

func (*UserPermission) Save

func (u *UserPermission) Save()

func (UserPermission) String

func (u UserPermission) String() string

Directories

Path Synopsis
cmd
uadmin
The MIT License (MIT)
The MIT License (MIT)
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