jwt validation, getting the correct database
This commit is contained in:
@ -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
|
@ -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
|
Reference in New Issue
Block a user