Select Git revision
constants.go
-
Mathilde Hertaas authoredMathilde Hertaas authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
auth.go 4.29 KiB
package auth
import (
"crypto/sha256"
logging "dcsg2900-threattotal/logs"
"dcsg2900-threattotal/utils"
"encoding/json"
"fmt"
"time"
)
// Authenticate function, takes a code or a token,
// returns a bool, and if the input is a valid code a hash is also returned.
func Authenticate(code string, token string) (authenticated bool, hash string) {
authenticated = false
var err bool
if code != "" {
fmt.Println("Hash is not empty")
hash, err = addUser(code)
fmt.Println("hash is: ", hash)
if !err {
return
}
authenticated = true
fmt.Println("Returning: ", authenticated, hash)
return authenticated, hash
} else if token != "" {
_, authenticated = getAuth(token)
return
}
return
}
// Func which adds a user to the database and returns a code
func addUser(code string) (hash string, auth bool) {
tokenResponse, auth := CodeToToken(code)
if !auth {
return "", false
}
//hash = tokenToHash(tokenResponse)
// Add the hash to the database with tokenResponse as the value
return tokenResponse, true
}
// Func which takes a code and returns an authentication token.
// Inspiration from the go-oidc examples: https://github.com/coreos/go-oidc/blob/v3/example/userinfo/app.go
// and https://github.com/coreos/go-oidc/blob/v3/example/idtoken/app.go
func CodeToToken(code string) (token string, authenticated bool) {
// Get the token
oauth2Token, err := utils.Config.Exchange(utils.Ctx, code)
if err != nil {
fmt.Println("Failed to exchange token: " + err.Error())
return "", false
}
// Extra fields contain: scope, token_type and id_token
// Get the jwt
rawIDToken, error := oauth2Token.Extra("id_token").(string)
if !error {
fmt.Println("No jwt returned.")
logging.Logerror(nil, "No JWT returned AUTH.go:")
return "", false
}
// Verify the jwt
idToken, err := utils.Verifier.Verify(utils.Ctx, rawIDToken)
if err != nil {
fmt.Println("Failed to validate the jwt.")
logging.Logerror(err, "Failed to validate JWT Auth.GO: ")