src.dualinventive.com/go/mtinfo-go/auth.go

137 lines
2.9 KiB
Go

package mtinfo
import (
"crypto/rsa"
"io/ioutil"
"github.com/dgrijalva/jwt-go.git"
auth "src.dualinventive.com/go/authentication-service/grpc"
)
//AuthServiceClient contains authentication related operations
type AuthServiceClient interface {
Login(username, companyCode, password string) (string, error)
Logout(token string) error
VerifyToken(token string, rights ...string) (bool, error)
VerifyTokenRemotely(token string, rights ...string) (bool, error)
Me(token string) (*User, error)
RequestPasswordReset(username string) error
RedeemPasswordReset(username, resetCode, password, passwordVerify string) error
ListTokens(token string) (OpaqueTokens, error)
DeleteToken(token string, opaqueToken string) error
UserAgent() string
SetUserAgent(string)
}
//User is a table structure definition
type User struct {
ID uint
Name string
Company Company
Roles []Role
}
func newUser(user *auth.User) User {
return User{
ID: uint(user.UserId),
Name: user.UserName,
Company: newCompany(user.Company),
Roles: newRoles(user.Roles),
}
}
//Company reflects a company record of company table.
type Company struct {
ID uint
Code string
Name string
}
func newCompany(company *auth.Company) Company {
return Company{
ID: uint(company.Id),
Name: company.Name,
Code: company.Code,
}
}
//Role reflects a role record of the roles table.
type Role struct {
Name string
Rights []Right
}
func newRoles(roles []*auth.Role) []Role {
mapped := []Role{}
for _, role := range roles {
mapped = append(mapped, Role{
Name: role.Name,
Rights: newRights(role.Rights),
})
}
return mapped
}
//Right reflects a right of the rights table.
type Right string
func newRights(rights []string) []Right {
mapped := []Right{}
for _, right := range rights {
mapped = append(mapped, Right(right))
}
return mapped
}
//OpaqueTokens contains a map of opaque token <-> user agent.
type OpaqueTokens map[string]string
func newOpaqueTokens(tokens []*auth.OpaqueToken) OpaqueTokens {
mapped := map[string]string{}
for _, token := range tokens {
mapped[token.OpaqueId] = token.UserAgent
}
return mapped
}
func configurePublicKey(filepath string) (*rsa.PublicKey, error) {
f, err := ioutil.ReadFile(filepath) //nolint:gosec
if err != nil {
return nil, err
}
return jwt.ParseRSAPublicKeyFromPEM(f)
}
//Claims contains token data which will be encrypted and form the JWT token including headers and signing.
type Claims struct {
jwt.StandardClaims
User string `json:"user"`
UserAgent string `json:"userAgent"`
OpaqueID string `json:"opaqueId"`
Rights Rights `json:"rights"`
}
//Rights is a list of right-codes
type Rights []string
func (c Rights) containsAll(rights ...string) bool {
for _, r := range rights {
if !c.contains(r) {
return false
}
}
return true
}
func (c Rights) contains(right string) bool {
for _, r := range c {
if r == right {
return true
}
}
return false
}