set uuid and refresh token path

This commit is contained in:
Matthieu Lamalle 2020-07-21 11:08:01 +02:00
parent 8163b9cc07
commit 8a8d06cb7c
7 changed files with 280 additions and 97 deletions

31
api.http Normal file
View File

@ -0,0 +1,31 @@
@host = http://localhost:3001
@authToken = ""
@refreshToken = ""
# Register user
# @name register
POST {{host}}/api/user/new
content-type: application/json
{
"email": "toto@test.com",
"password": "toto"
}
###
#Login user
# @name login
POST {{host}}/api/user/login
content-type: application/json
{
"email": "toto@test.com",
"password": "toto"
}
###
#Refresh user
@refreshToken = {{login.response.body.refresh_token}}
# @name refresh
POST {{host}}/api/user/refresh
Authorization: Bearer {{refreshToken}}

5
go.mod
View File

@ -5,7 +5,12 @@ go 1.14
require ( require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-chi/chi v4.1.2+incompatible github.com/go-chi/chi v4.1.2+incompatible
github.com/gofrs/uuid v3.3.0+incompatible
github.com/jinzhu/gorm v1.9.14 github.com/jinzhu/gorm v1.9.14
github.com/joho/godotenv v1.3.0 github.com/joho/godotenv v1.3.0
github.com/satori/go.uuid v1.2.0 // indirect
github.com/yuin/goldmark v1.1.33 // indirect
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899
golang.org/x/net v0.0.0-20200707034311-ab3426394381 // indirect
golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6 // indirect
) )

28
go.sum
View File

@ -10,6 +10,9 @@ github.com/go-chi/chi v4.1.2+incompatible h1:fGFk2Gmi/YKXk0OmGfBh0WgmN3XB8lVnEyN
github.com/go-chi/chi v4.1.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= github.com/go-chi/chi v4.1.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/gofrs/uuid v1.2.0 h1:coDhrjgyJaglxSjxuJdqQSSdUpG3w6p1OwN2od6frBU=
github.com/gofrs/uuid v3.3.0+incompatible h1:8K4tyRfvU1CYPgJsveYFQMhpFd/wXNM7iK6rR7UHz84=
github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/jinzhu/gorm v1.9.14 h1:Kg3ShyTPcM6nzVo148fRrcMO6MNKuqtOUwnzqMgVniM= github.com/jinzhu/gorm v1.9.14 h1:Kg3ShyTPcM6nzVo148fRrcMO6MNKuqtOUwnzqMgVniM=
@ -24,18 +27,43 @@ github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4=
github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-sqlite3 v1.14.0 h1:mLyGNKR8+Vv9CAU7PphKa2hkEqxxhn8i32J6FPj1/QA= github.com/mattn/go-sqlite3 v1.14.0 h1:mLyGNKR8+Vv9CAU7PphKa2hkEqxxhn8i32J6FPj1/QA=
github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/yuin/goldmark v1.1.32 h1:5tjfNdR2ki3yYQ842+eX2sQHeiwpKJ0RnHO4IYOc4V8=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.33 h1:Q0PzHNn2h69wYmmE2SukzuQe0VBwErZrgJ5ZB8od6zQ=
github.com/yuin/goldmark v1.1.33/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 h1:DZhuSZLsGlFL4CmhA8BcRA0mnthyA/nZ00AqCUo7vHg= golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 h1:DZhuSZLsGlFL4CmhA8BcRA0mnthyA/nZ00AqCUo7vHg=
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200625001655-4c5254603344 h1:vGXIOMxbNfDTk/aXCmfdLgkrSV+Z2tcbze+pEc3v5W4=
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200707034311-ab3426394381 h1:VXak5I6aEWmAXeQjA+QSZzlgNrpq9mjcfDemuexIKsU=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6 h1:nULzSsKgihxFGLnQFv2T7lE5vIhOtg8ZPpJHapEt7o0=
golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -23,6 +23,7 @@ func InitializeRouter() chi.Router {
// Middleware routes // Middleware routes
r.Post("/user/new", jwtmiddleware.CreateAccount) r.Post("/user/new", jwtmiddleware.CreateAccount)
r.Post("/user/login", jwtmiddleware.Authenticate) r.Post("/user/login", jwtmiddleware.Authenticate)
r.Post("/user/refresh", jwtmiddleware.Refresh)
}) })

View File

@ -2,10 +2,15 @@ package middleware
import ( import (
"encoding/json" "encoding/json"
"log" "errors"
"fmt"
"net/http" "net/http"
"strconv"
"time"
"github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go"
"github.com/gofrs/uuid"
"github.com/joho/godotenv"
"strings" "strings"
@ -16,31 +21,56 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
/* var (
JWT claims struct accessExpires int
*/ refreshExpiration int
type Token struct { audience string
UserId uint subject string
)
func init() {
e := godotenv.Load() //Load .env file
if e != nil {
fmt.Print(e)
}
var err error
accessExpires, err = strconv.Atoi(os.Getenv("access_expiration"))
if err != nil {
panic(err)
}
refreshExpiration, err = strconv.Atoi(os.Getenv("access_expiration"))
if err != nil {
panic(err)
}
audience = os.Getenv("audience")
subject = os.Getenv("subject")
}
// TokenDetails struct
type TokenDetails struct {
UserID uuid.UUID `json:"user_id"`
jwt.StandardClaims jwt.StandardClaims
} }
//a struct to rep user account //Account struct to rep user account
type Account struct { type Account struct {
gorm.Model ID uuid.UUID `gorm:"type:uuid;primary_key;"`
Email string `json:"email"` Email string `json:"email"`
Password string `json:"password"` Password string `json:"password,omitempty"`
Token string `json:"token";sql:"-"` Token string `json:"access_token,omitempty" sql:"-"`
RefreshToken string `json:"refresh_token,omitempty" sql:"-"`
TokenExpiresAt string `json:"-"`
} }
//Validate incoming user details... //Validate incoming user details...
func (account *Account) Validate() (map[string]interface{}, bool) { func (account *Account) Validate() (map[string]interface{}, bool) {
if !strings.Contains(account.Email, "@") { if !strings.Contains(account.Email, "@") {
return Message(false, "Email address is required"), false return message(false, "Email address is required"), false
} }
if len(account.Password) < 1 { if len(account.Password) < 1 {
return Message(false, "Password is required"), false return message(false, "Password is required"), false
} }
//Email must be unique //Email must be unique
@ -49,15 +79,16 @@ func (account *Account) Validate() (map[string]interface{}, bool) {
//check for errors and duplicate emails //check for errors and duplicate emails
err := GetDB().Table("accounts").Where("email = ?", account.Email).First(temp).Error err := GetDB().Table("accounts").Where("email = ?", account.Email).First(temp).Error
if err != nil && err != gorm.ErrRecordNotFound { if err != nil && err != gorm.ErrRecordNotFound {
return Message(false, "Connection error. Please retry"), false return message(false, "Connection error. Please retry"), false
} }
if temp.Email != "" { if temp.Email != "" {
return Message(false, "Email address already in use by another user."), false return message(false, "Email address already in use by another user."), false
} }
return Message(false, "Requirement passed"), true return message(false, "Requirement passed"), true
} }
// Create user account
func (account *Account) Create() map[string]interface{} { func (account *Account) Create() map[string]interface{} {
if resp, ok := account.Validate(); !ok { if resp, ok := account.Validate(); !ok {
@ -69,53 +100,89 @@ func (account *Account) Create() map[string]interface{} {
GetDB().Create(account) GetDB().Create(account)
if account.ID <= 0 { if account.ID == uuid.Nil {
return Message(false, "Failed to create account, connection error.") return message(false, "Failed to create account, connection error.")
} }
//Create new JWT token for the newly registered account
tk := &Token{UserId: account.ID}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
account.Token = tokenString
account.Password = "" //delete password account.Password = "" //delete password
response := Message(true, "Account has been created") response := message(true, "Account has been created")
response["account"] = account response["account"] = account
return response return response
} }
// Login and provides user token
func Login(email, password string) map[string]interface{} { func Login(email, password string) map[string]interface{} {
account := &Account{} account := &Account{}
err := GetDB().Table("accounts").Where("email = ?", email).First(account).Error err := GetDB().Table("accounts").Where("email = ?", email).First(account).Error
if err != nil { if err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
return Message(false, "Email address not found") return message(false, "Email address not found")
} }
return Message(false, "Connection error. Please retry") return message(false, "Connection error. Please retry")
} }
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password)) err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password))
if err != nil && err == bcrypt.ErrMismatchedHashAndPassword { //Password does not match! if err != nil && err == bcrypt.ErrMismatchedHashAndPassword { //Password does not match!
return Message(false, "Invalid login credentials. Please try again") return message(false, "Invalid login credentials. Please try again")
} }
//Worked! Logged In //Worked! Logged In
account.Password = "" account.Password = ""
account.GenerateTokenPair()
//account.CreateAuth(td)
//Create JWT token resp := make(map[string]interface{})
tk := &Token{UserId: account.ID} resp["access_token"] = account.Token
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk) resp["refresh_token"] = account.RefreshToken
tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
account.Token = tokenString //Store the token in the response
resp := Message(true, "Logged In")
resp["account"] = account
return resp return resp
} }
func GetUser(u uint) *Account { // GenerateTokenPair return access_token and refresh_token pair
func (account *Account) GenerateTokenPair() (*TokenDetails, error) {
//Create JWT token
tk := &TokenDetails{
account.ID,
jwt.StandardClaims{
IssuedAt: time.Now().Unix(),
ExpiresAt: time.Now().Add(time.Second * time.Duration(accessExpires)).Unix(),
Audience: audience,
Subject: subject,
},
}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, err := token.SignedString([]byte(os.Getenv("access_token_password")))
if err != nil {
return nil, err
}
account.Token = tokenString //Store the token in the response
reftk := &TokenDetails{
account.ID,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Minute * time.Duration(refreshExpiration)).Unix(),
},
}
refreshtoken := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), reftk)
refreshtokenString, err := refreshtoken.SignedString([]byte(os.Getenv("refresh_token_password")))
if err != nil {
return nil, err
}
account.RefreshToken = refreshtokenString //Store the token in the response
return reftk, nil
}
// CreateAuth stores refresh_token expires
// func (account *Account) CreateAuth(td *TokenDetails) {
// rt := time.Unix(td.ExpiresAt, 0)
// db.Model(&account).Update(account.TokenExpiresAt, rt.String())
// }
// GetUser in the database
func GetUser(u uuid.UUID) *Account {
acc := &Account{} acc := &Account{}
GetDB().Table("accounts").Where("id = ?", u).First(acc) GetDB().Table("accounts").Where("id = ?", u).First(acc)
@ -127,41 +194,126 @@ func GetUser(u uint) *Account {
return acc return acc
} }
// CreateAccount middleware to create user account
var CreateAccount = func(w http.ResponseWriter, r *http.Request) { var CreateAccount = func(w http.ResponseWriter, r *http.Request) {
account := &Account{} account := &Account{}
err := json.NewDecoder(r.Body).Decode(account) //decode the request body into struct and failed if any error occur err := json.NewDecoder(r.Body).Decode(account) //decode the request body into struct and failed if any error occur
log.Println(err)
if err != nil { if err != nil {
Respond(w, Message(false, "Invalid request")) respond(w, message(false, "Invalid request"))
return return
} }
resp := account.Create() //Create account resp := account.Create() //Create account
Respond(w, resp) respond(w, resp)
} }
// Authenticate middleware to authenticate the user
var Authenticate = func(w http.ResponseWriter, r *http.Request) { var Authenticate = func(w http.ResponseWriter, r *http.Request) {
account := &Account{} account := &Account{}
err := json.NewDecoder(r.Body).Decode(account) //decode the request body into struct and failed if any error occur err := json.NewDecoder(r.Body).Decode(account) //decode the request body into struct and failed if any error occur
log.Println(err)
if err != nil { if err != nil {
Respond(w, Message(false, "Invalid request")) respond(w, message(false, "Invalid request"))
return return
} }
resp := Login(account.Email, account.Password) resp := Login(account.Email, account.Password)
Respond(w, resp) respond(w, resp)
} }
func Message(status bool, message string) map[string]interface{} { // Refresh middleware to authenticate the user
log.Println(message) var Refresh = func(w http.ResponseWriter, r *http.Request) {
tk, err := ValidateToken(w, r)
if err != nil {
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
response := message(true, "Refreshed expired")
respond(w, response)
return
}
// check if user exists in database
acc := GetUser(tk.UserID)
if acc == nil {
respond(w, message(false, "User not found"))
return
}
acc.Password = ""
acc.GenerateTokenPair()
//account.CreateAuth(td)
resp := make(map[string]interface{})
resp["access_token"] = acc.Token
resp["refresh_token"] = acc.RefreshToken
//update refresh expirity
// rt := time.Now().Add(time.Minute * time.Duration(refreshExpiration)).Unix()
// log.Println(rt)
// db.Model(&acc).Update(acc.TokenExpiresAt, rt)
respond(w, resp)
}
// ValidateToken to check if token is valid
func ValidateToken(w http.ResponseWriter, r *http.Request) (*TokenDetails, error) {
var pwd string
urltomatch := r.URL.String()
if urltomatch == "/api/user/refresh" {
pwd = "refresh_token_password"
} else {
pwd = "access_token_password"
}
response := make(map[string]interface{})
tk := &TokenDetails{}
bearToken := r.Header.Get("Authorization") //Grab the token from the header
if bearToken == "" { //Token is missing, returns with error code 403 Unauthorized
response = message(false, "Missing auth token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
respond(w, response)
return tk, errors.New("Missing auth token")
}
splitted := strings.Split(bearToken, " ") //The token normally comes in format `Bearer {token-body}`, we check if the retrieved token matched this requirement
if len(splitted) != 2 {
response = message(false, "Invalid/Malformed auth token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
respond(w, response)
return tk, errors.New("Invalid/Malformed auth token")
}
tokenPart := splitted[1] //Grab the token part, what we are truly interested in
token, err := jwt.ParseWithClaims(tokenPart, tk, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv(pwd)), nil
})
if err != nil { //Malformed token, returns with http code 403 as usual
response = message(false, "Malformed authentication token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
respond(w, response)
return tk, errors.New("Malformed authentication token")
}
if !token.Valid { //Token is invalid, maybe not signed on this server
response = message(false, "Token is not valid.")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
respond(w, response)
return tk, errors.New("Token is not valid")
}
return tk, nil
}
func message(status bool, message string) map[string]interface{} {
return map[string]interface{}{"status": status, "message": message} return map[string]interface{}{"status": status, "message": message}
} }
func Respond(w http.ResponseWriter, data map[string]interface{}) { func respond(w http.ResponseWriter, data map[string]interface{}) {
log.Println(data)
w.Header().Add("Content-Type", "application/json") w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(data) json.NewEncoder(w).Encode(data)
} }

View File

@ -2,14 +2,9 @@ package middleware
import ( import (
"context" "context"
"fmt"
"log" "log"
"net/http" "net/http"
"os"
"strings"
jwt "github.com/dgrijalva/jwt-go"
) )
// JwtAuthentication is a Jwt Auth controller with postgres database // JwtAuthentication is a Jwt Auth controller with postgres database
@ -17,7 +12,7 @@ var JwtAuthentication = func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
notAuth := []string{"/api/user/new", "/api/user/login"} //List of endpoints that doesn't require auth notAuth := []string{"/api/user/new", "/api/user/login", "/api/user/refresh"} //List of endpoints that doesn't require auth
requestPath := r.URL.Path //current request path requestPath := r.URL.Path //current request path
//check if request does not need authentication, serve the request if it doesn't need it //check if request does not need authentication, serve the request if it doesn't need it
@ -28,53 +23,14 @@ var JwtAuthentication = func(next http.Handler) http.Handler {
return return
} }
} }
tk, err := ValidateToken(w, r)
response := make(map[string]interface{}) if err != nil {
tokenHeader := r.Header.Get("Authorization") //Grab the token from the header
if tokenHeader == "" { //Token is missing, returns with error code 403 Unauthorized
response = Message(false, "Missing auth token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
Respond(w, response)
return
}
splitted := strings.Split(tokenHeader, " ") //The token normally comes in format `Bearer {token-body}`, we check if the retrieved token matched this requirement
if len(splitted) != 2 {
response = Message(false, "Invalid/Malformed auth token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
Respond(w, response)
return
}
tokenPart := splitted[1] //Grab the token part, what we are truly interested in
tk := &Token{}
log.Println(splitted)
token, err := jwt.ParseWithClaims(tokenPart, tk, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("token_password")), nil
})
if err != nil { //Malformed token, returns with http code 403 as usual
response = Message(false, "Malformed authentication token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
Respond(w, response)
return
}
if !token.Valid { //Token is invalid, maybe not signed on this server
response = Message(false, "Token is not valid.")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
Respond(w, response)
return return
} }
//Everything went well, proceed with the request and set the caller to the user retrieved from the parsed token //Everything went well, proceed with the request and set the caller to the user retrieved from the parsed token
fmt.Sprintf("User %", tk) //Useful for monitoring log.Printf("User %v", tk) //Useful for monitoring
ctx := context.WithValue(r.Context(), "user", tk.UserId) ctx := context.WithValue(r.Context(), "user", tk.UserID)
r = r.WithContext(ctx) r = r.WithContext(ctx)
next.ServeHTTP(w, r) //proceed in the middleware chain! next.ServeHTTP(w, r) //proceed in the middleware chain!
}) })

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/gofrs/uuid"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" _ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/joho/godotenv" "github.com/joho/godotenv"
@ -39,3 +40,12 @@ func init() {
func GetDB() *gorm.DB { func GetDB() *gorm.DB {
return db return db
} }
// BeforeCreate will set a UUID rather than numeric ID.
func (accont *Account) BeforeCreate(scope *gorm.Scope) error {
uuid, err := uuid.NewV4()
if err != nil {
return err
}
return scope.SetColumn("ID", uuid)
}