jwt validation, getting the correct database

This commit is contained in:
2018-11-07 20:13:26 +01:00
parent 549d91fbb4
commit 3347161ae9
13 changed files with 125 additions and 62 deletions

View File

@ -2,10 +2,12 @@ package services
import (
"database/sql"
"errors"
"fmt"
"os"
"github.com/astaxie/beego/orm"
jwt "github.com/dgrijalva/jwt-go"
)
var dbs map[string]*sql.DB
@ -27,13 +29,30 @@ func InitCompanyService() {
}
// GetDatabase Get orm and user information
func GetDatabase(token string) {
func GetDatabase(tokenString string) (jwt.MapClaims, *sql.DB, error) {
// validate token
// retrieve correct user/database
// check if open first
// try to open second
// return error otherwise
valid, token := Validate(tokenString)
if !valid {
return nil, nil, errors.New("Token is invalid")
}
tokenMap := token.Claims.(jwt.MapClaims)
companyName := tokenMap["companyName"].(string)
if dbs[companyName] != nil {
fmt.Println("DB Already open")
return tokenMap, dbs[companyName], nil
}
conStr := fmt.Sprintf("host=127.0.0.1 port=5435 user=postgres password=postgre dbname=%s sslmode=disable", tokenMap["companyName"])
fmt.Println(conStr)
db, err := sql.Open("postgres", conStr)
if err != nil {
return nil, nil, err
}
// return db with orm or error
return tokenMap, db, nil
}
// CreateDatabase Create a database by copying the template

View File

@ -9,18 +9,22 @@ import (
var hmacSecret []byte
// GenerateSecret generate the secret to verify JWTs
func GenerateSecret() []byte {
b := make([]byte, 32)
rand.Read(b)
return b
}
func InitAuthService() {
// InitJWTService generate the secret to verify JWTs and store it in memory
func InitJWTService() {
hmacSecret = GenerateSecret()
fmt.Println("InitJWTService", hmacSecret)
// TODO: This needs to be replaced with reading rsa keys, there needs to be a automatic generation of these if they do not exist
}
// Validate a jwt tokenstring
func Validate(Token string) (bool, jwt.Token) {
token, err := jwt.Parse(Token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
@ -31,6 +35,7 @@ func Validate(Token string) (bool, jwt.Token) {
})
if err == nil && token.Valid {
fmt.Println("Token is valid")
return true, *token
}
@ -39,6 +44,7 @@ func Validate(Token string) (bool, jwt.Token) {
return false, *token
}
// CreateToken create a new jwt token with the provided claims
func CreateToken(Claims jwt.MapClaims) string {
// Create a new token object, specifying signing method and the claims