Code Monkey home page Code Monkey logo

auth's Introduction

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

auth's People

Contributors

chenxin0723 avatar cryptix avatar defer avatar dependabot[bot] avatar easonlin404 avatar jasonweng avatar jinzhu avatar raven-chen avatar sunfmin avatar zealllot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth's Issues

更新版本登录失败

(/home/abner/work/go/src/github.com/qor/auth/providers/password/handlers.go:27)
[2018-10-26 15:46:07] Error 1054: Unknown column 'basics.provider' in 'where clause'

(/home/abner/work/go/src/github.com/qor/auth/providers/password/handlers.go:27)
[2018-10-26 15:46:07] [1.36ms] SELECT * FROM auth_identities WHERE auth_identities.deleted_at IS NULL AND ((basics.provider = 'password') AND (basics.uid = '[email protected]'))
[0 rows affected or returned ]

(/home/abner/work/go/src/github.com/qor/auth/user_storer.go:45)
[2018-10-26 15:46:07] Error 1054: Unknown column 'basics.provider' in 'where clause'

(/home/abner/work/go/src/github.com/qor/auth/user_storer.go:45)
[2018-10-26 15:46:07] [1.18ms] SELECT * FROM auth_identities WHERE auth_identities.deleted_at IS NULL AND ((basics.provider = 'password') AND (basics.uid = '[email protected]')) ORDER BY auth_identities.id ASC LIMIT 1
[0 rows affected or returned ]

access deny should not always redirect

Hi @bodhi @jinzhu

Can you share your thought here?

https://github.com/qor/auth/blob/master/authority/authority.go#L33

https://github.com/qor/auth/blob/master/authority/authority.go#L81

After valid the roles, I want write proto(json) message to front-end instead of redirect to login page.
I think the how to handle access deny is a configurable behavior.

// Config authority config
type Config struct {
	Auth                          AuthInterface
	Role                          *roles.Role
	// RedirectPathAfterAccessDenied string
        AccessDenyHandler func(w http.ResponseWriter, req *http.Request, auth AuthInterface)
}

go-github implementation error

Hi guys,

Hope you are all well !

Will fetching dependencies, I have the following error about go-github.

# github.com/qor/qor-example/vendor/github.com/qor/auth/providers/github
vendor/github.com/qor/auth/providers/github/github.go:87:37: too many arguments in call to client.Users.Get
	have (context.Context, string)
	want (string)

Can you use go.mod or glide for versioning vendors ?

Btw.
I try to create a docker-compose and Dockerfile
https://github.com/x0rzkov/qor-example/blob/compose/docker-compose.yml
https://github.com/x0rzkov/qor-example/blob/compose/Dockerfile

Thanks in advance.

Cheers,
X

learning video

hello everyone
I have searched in google for documentation or learning video or more example about qor-auth
but I found nothing
unfortunately qor has very very bad docs
can any body make video or something else about using
qor/auth
qor/admin
qor/auth-them

Integration in qor auth

Now for integration, "auth_boss" of the old version is used. Can I use this module instead of "auth_boss". But then you need to do another function to change the password and restore it.

jwt for api endpoints

Hi guys, @raven-chen ,

Hope you are all well !

I created the website https://paper2code.com/ with the qor framework and I need to implement a more advanced restful api functions.

So I have read the documentation about the RESTFul api but I did not find a way to implement a JWT token to query the api endpoints.

Just to be sure, and that's a very important question as I need to implement that asap, how can I implement gin-jwt with qor or as a use case with qor-example ?

Thanks for you insights or snippets by advance.

Cheers,
X

any API documentation ?

related to #23 , actually I don't need any views. If the library can provide an API it is ok, but checking around I cant find any API documentation. For things like login/logout/oauth login etc. Some examples / documentation would be great.

Client/Server auth

Assume you have a web client, how would you handle the client/server authorization?
Must we redirect the user from the browser to the server/auth/ path and handle login there or is there a way to handle the auth client side and just POST the data to the server to get a session token?

Undefined config & models when Initializing Auth

When using the example code from Readme

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

Where to get config & models from ?

'Unknow column...' error

I tried to run an authentication example but has an error :
Error 1054: Unknown column 'basics.provider' in 'where clause' . Here is my source code:

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/jinzhu/gorm”
)

var (
  // Initialize gorm DB
  gormDB, _ = gorm.Open("mysql", "root:123456@/qor_example?charset=utf8&parseTime=True&loc=Local")

  // 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",
  }))

  // 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))
}

Change email templates

Is there a way to customize views inside github.com/qor/auth/providers/password/views?

Compilation errors while trying to run sample application in README.md

  1. I copied the sample application into a main.go in a directory.
  2. I ran dep init -v.
  3. I ran go run main.go.

This throws the following errors:

vendor/github.com/qor/mailer/mailer.go:39:29: cannot use nil as type string in argument to render.New
vendor/github.com/qor/mailer/mailer.go:40:16: config.Render.SetAssetFS undefined (type *render.Render has no field or method SetAssetFS)
vendor/github.com/qor/mailer/template.go:46:83: mailer.Config.Render.Layout(t.Layout + ".text").Funcs(t.funcMap).Render undefined (type *render.Template has no field or method Render, but does have render.render)
vendor/github.com/qor/mailer/template.go:50:83: mailer.Config.Render.Layout(t.Layout + ".html").Funcs(t.funcMap).Render undefined (type *render.Template has no field or method Render, but does have render.render)
vendor/github.com/qor/mailer/template.go:52:82: mailer.Config.Render.Layout(t.Layout).Funcs(t.funcMap).Render undefined (type *render.Template has no field or method Render, but does have render.render)
vendor/github.com/qor/mailer/template.go:56:58: mailer.Config.Render.Funcs(t.funcMap).Render undefined (type *render.Template has no field or method Render, but does have render.render)
vendor/github.com/qor/mailer/template.go:60:58: mailer.Config.Render.Funcs(t.funcMap).Render undefined (type *render.Template has no field or method Render, but does have render.render)
vendor/github.com/qor/mailer/template.go:62:65: mailer.Config.Render.Funcs(t.funcMap).Render undefined (type *render.Template has no field or method Render, but does have render.render)
# auth/vendor/github.com/qor/session/gorilla
vendor/github.com/qor/session/gorilla/gorilla.go:26:12: undefined: utils.ContextKey

Some of the code, where nil is passed in place of integer, seems incorrect.

SignedString is an empty string

I think there is an issue with the token signing, which is that the value of SignedString is never set (so it is the default empty string) but it is used for signing tokens:

signedToken, _ := token.SignedString([]byte(sessionStorer.SignedString))

google auth not working

while trying to use google authentication, we get the following error.

(Error 1054: Unknown column 'basics.provider' in 'where clause')

Registration email not working

After setting smtp details while sending emails there is error :

failed to find template: auth/confirmation.text

We are using clean theme for auth .

failed to find template: auth/confirmation.text
TO: [email protected]
Subject: Please confirm your account

Content-Type: text/html; charset=UTF-8

Please click on the below link to validate your email address:

http://localhost:7000/auth/password/confirm?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm92aWRlciI6InBhc3N3b3JkIiwidXNlcmlkIjoiMzE0IiwianRpIjoidGVzdDFAdGVzdC5jb20iLCJzdWIiOiJjb25maXJtIn0.UDQennBXY_0k9qaL-YhagVleeh-yoK_1NBXxn7gA6L4

views not working

I just imported this and trying login / logout etc. I get

failed to find template: auth/login

I'm using go1.11.1, deps installed with modules.

I also tried installing the clean theme, but didnt help.

Password with Registration Fails

I am unable to register a new user with a password. The UI states invalid account. The server output states (pq: missing FROM-clause entry for table "basics"). I am using code inspired by this project's README.md.

package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"github.com/qor/auth"
	"github.com/qor/auth/auth_identity"
	"github.com/qor/auth/providers/password"
	"github.com/qor/session/manager"

	"net/http"
)

var (
	// Initialize gorm DB
	gormDB, _ = gorm.Open("postgres", "host=localhost port=5432 user=postgres dbname=postgres password=postgres sslmode=disable")

	// 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{}))
}

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

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

Single sign on implementation in qor

Hi,

Can we connect qor to third party idp like onelogin , auth0 etc?
Please guide me if anything we can do to replace current auth to sso

Thanks
Pankaj

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.