• Stars
    star
    677
  • Rank 66,694 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created over 7 years ago
  • Updated almost 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang Authentication solution

Auth

Auth is a modular authentication system for web development in Golang, it provides different authentication backends to accelerate your development.

Currently Auth has database password, github, google, facebook, twitter authentication support, and it is fairly easy to add other support based on Auth's Provider interface

Quick Start

Auth aims to provide an easy to use authentication system that don't require much developer's effort.

To use it, basic flow is:

  • Initialize Auth with configuration
  • Register some providers
  • Register it into router

Here is an example:

package main

import (
  "github.com/qor/auth"
  "github.com/qor/auth/auth_identity"
  "github.com/qor/auth/providers/github"
  "github.com/qor/auth/providers/google"
  "github.com/qor/auth/providers/password"
  "github.com/qor/auth/providers/facebook"
  "github.com/qor/auth/providers/twitter"
  "github.com/qor/session/manager"

  _ "github.com/mattn/go-sqlite3"

  "net/http"
)

var (
  // Initialize gorm DB
  gormDB, _ = gorm.Open("sqlite3", "sample.db")

  // Initialize Auth with configuration
  Auth = auth.New(&auth.Config{
    DB: gormDB,
  })
)

func init() {
  // Migrate AuthIdentity model, AuthIdentity will be used to save auth info, like username/password, oauth token, you could change that.
  gormDB.AutoMigrate(&auth_identity.AuthIdentity{})

  // Register Auth providers
  // Allow use username/password
  Auth.RegisterProvider(password.New(&password.Config{}))

  // Allow use Github
  Auth.RegisterProvider(github.New(&github.Config{
    ClientID:     "github client id",
    ClientSecret: "github client secret",
  }))

  // Allow use Google
  Auth.RegisterProvider(google.New(&google.Config{
    ClientID:     "google client id",
    ClientSecret: "google client secret",
    AllowedDomains: []string{}, // Accept all domains, instead you can pass a whitelist of acceptable domains
  }))

  // Allow use Facebook
  Auth.RegisterProvider(facebook.New(&facebook.Config{
    ClientID:     "facebook client id",
    ClientSecret: "facebook client secret",
  }))

  // Allow use Twitter
  Auth.RegisterProvider(twitter.New(&twitter.Config{
    ClientID:     "twitter client id",
    ClientSecret: "twitter client secret",
  }))
}

func main() {
  mux := http.NewServeMux()

  // Mount Auth to Router
  mux.Handle("/auth/", Auth.NewServeMux())
  http.ListenAndServe(":9000", manager.SessionManager.Middleware(mux))
}

That's it, then you could goto http://127.0.0.1:9000/auth/login to try Auth features, like login, logout, register, forgot/change password...

And it could be even easier with Auth Themes, you could integrate Auth into your application with few line configurations.

Usage

Auth has many configurations that could be used to customize it for different usage, lets start from Auth's Config.

Models

Auth has two models, model AuthIdentityModel is used to save login information, model UserModel is used to save user information.

The reason we save auth and user info into two different models, as we want to be able to link a user to mutliple auth info records, so a user could have multiple ways to login.

If this is not required for you, you could just set those two models to same one or skip set UserModel.

  • AuthIdentityModel

Different provider usually use different information to login, like provider password use username/password, github use github user ID, so for each provider, it will save those information into its own record.

You are not necessary to set AuthIdentityModel, Auth has a default definition of AuthIdentityModel, in case of you want to change it, make sure you have auth_identity.Basic embedded, as Auth assume you have same data structure in your database, so it could query/create records with SQL.

  • UserModel

By default, there is no UserModel defined, even though, you still be able to use Auth features, Auth will return used auth info record as logged user.

But usually your application will have a User model, after you set its value, when you register a new account from any provider, Auth will create/get a user with UserStorer, and link its ID to the auth identity record.

Customize views

Auth using Render to render pages, you could refer it for how to register func maps, extend views paths, also be sure to refer BindataFS if you want to compile your application into a binary.

If you want to preprend view paths, you could add them to ViewPaths, which would be helpful if you want to overwrite the default (ugly) login/register pages or develop auth themes like https://github.com/qor/auth_themes

Sending Emails

Auth using Mailer to send emails, by default, Auth will print emails to console, please configure it to send real one.

User Storer

Auth created a default UserStorer to get/save user based on your AuthIdentityModel, UserModel's definition, in case of you want to change it, you could implement your own User Storer

Session Storer

Auth also has a default way to handle sessions, flash messages, which could be overwrited by implementing Session Storer Interface.

By default, Auth is using session's default manager to save data into cookies, but in order to save cookies correctly, you have to register session's Middleware into your router, e.g:

func main() {
	mux := http.NewServeMux()

	// Register Router
	mux.Handle("/auth/", Auth.NewServeMux())
	http.ListenAndServe(":9000", manager.SessionManager.Middleware(mux))
}

Redirector

After some Auth actions, like logged, registered or confirmed, Auth will redirect user to some URL, you could configure which page to redirect with Redirector, by default, will redirct to home page.

If you want to redirect to last visited page, redirect_back is for you, you could configure it and use it as the Redirector, like:

var RedirectBack = redirect_back.New(&redirect_back.Config{
	SessionManager:  manager.SessionManager,
	IgnoredPrefixes: []string{"/auth"},
}

var Auth = auth.New(&auth.Config{
	...
	Redirector: auth.Redirector{RedirectBack},
})

BTW, to make it works correctly, redirect_back need to save last visisted URL into session with session manager for each request, that's means, you need to mount redirect_back, and SessionManager's middleware into router.

http.ListenAndServe(":9000", manager.SessionManager.Middleware(RedirectBack.Middleware(mux)))

Advanced Usage

Auth Themes

In order to save more developer's effort, we have created some auth themes.

It usually has well designed pages, if you don't much custom requirements, you could just have few lines to make Auth system ready to use for your application, for example:

import "github.com/qor/auth_themes/clean"

var Auth = clean.New(&auth.Config{
	DB:         db.DB,
	Render:     config.View,
	Mailer:     config.Mailer,
	UserModel:  models.User{},
})

Check Auth Theme's document for How To use/create Auth themes

Authorization

Authentication is the process of verifying who you are, Authorization is the process of verifying that you have access to something.

Auth package not only provides Authentication, but also Authorization, please checkout authority for more details

More Repositories

1

qor

QOR is a set of libraries written in Go that abstracts common features needed for business applications, CMSs, and E-commerce systems.
Go
5,198
star
2

qor-example

An example application showcasing the QOR SDK
Go
1,241
star
3

admin

Qor Admin - Instantly create a beautiful, cross platform, configurable Admin Interface and API for managing your data in minutes.
JavaScript
898
star
4

transition

Transition is a Golang state machine implementation
Go
425
star
5

roles

Roles is an authorization library for Golang
Go
140
star
6

validations

Validations is a GORM extension, used to validate models when creating, updating
Go
128
star
7

i18n

I18n is a golang implementation, provides internationalization support for your application, with different backends support
Go
105
star
8

worker

Worker run jobs in background at scheduled time
Go
61
star
9

media

Media add uploading files to cloud or other destinations with support for image cropping and resizing features to any structs
JavaScript
60
star
10

oss

QOR OSS provides common interface to operate files in cloud storage/filesystem
Go
57
star
11

amazon-pay-sdk-go

Amazon Pay Go SDK
Go
31
star
12

mailer

Mail solution
Go
23
star
13

audited

Audited is used to log last UpdatedBy and CreatedBy for your models
Go
21
star
14

auth_themes

Auth Themes
Go
20
star
15

media_library

Abandoned, use https://github.com/qor/media instead
Go
20
star
16

bindatafs

Compile QOR templates into binary with go-bindata
Go
19
star
17

l10n

L10n make your resources(models) be able to localize into different locales
Go
18
star
18

exchange

QOR exchange provides conversion (import/export) functionality for any Qor.Resource to CSV, Excel file
Go
17
star
19

gomerchant

Stripe, Paygent, and Amazon Pay Adaptors
Go
17
star
20

render

Render Templates
Go
16
star
21

seo

SEO module for QOR3
Go
14
star
22

sorting

Sorting: adds sorting and reordering abilities to your models.
JavaScript
12
star
23

publish2

Version Control with Schedule
Go
11
star
24

widget

Qor Widget - Define some customizable, shareable HTML widgets for different pages
Go
11
star
25

session

Session management
Go
8
star
26

filebox

Filebox could be used to provide access permission control for files, directories
Go
8
star
27

doc

QOR3 documentation
CSS
6
star
28

publish

Publish allow user update a resource but do not show the change in website until it is get "published" for GORM-backend models
Go
6
star
29

activity

Qor Activity: add Comment and Track data/state changes to any Qor Resource support to admin interface
Go
6
star
30

notification

QOR Notification
Go
6
star
31

slug

Slug is an extension for qor.
JavaScript
6
star
32

responder

Responder: Respond differently according to request's accepted mime type
Go
6
star
33

location

Qor Location - Make your struct support pick up location from google map in Qor Admin
JavaScript
5
star
34

assetfs

AssetFileSystem
Go
5
star
35

middlewares

Middlewares Management
Go
5
star
36

serializable_meta

Serializable meta
Go
4
star
37

action_bar

Action Bar in QOR3
Go
4
star
38

cache

Cache Store
Go
4
star
39

redirect_back

A Golang HTTP Handler that redirect back to last URL saved in session
Go
4
star
40

page_builder

Page Builder
JavaScript
3
star
41

metas

Meta Types for Admin
JavaScript
3
star
42

log

Qor Logger
Go
3
star
43

help

Help for QOR ADMIN
JavaScript
3
star
44

banner_editor

Banner Editor in QOR3
JavaScript
2
star
45

application

Application
Go
2
star
46

qor-example-cases

Learn QOR3 by examples
Go
2
star
47

wildcard_router

WildcardRouter handles dynamic routes
Go
2
star
48

variations

Variations
JavaScript
2
star
49

app

App Generator - WIP
Swift
1
star