tiny-url-ex/controller.plugin/token/main.go

61 lines
1.3 KiB
Go

package main
import (
"crypto/sha512"
"encoding/hex"
"git.xdrm.io/example/aicra/db"
"git.xdrm.io/go/aicra/api"
"git.xdrm.io/go/aicra/driver"
e "git.xdrm.io/go/aicra/err"
"strconv"
"time"
)
func main() {}
type TokenController int
func Export() driver.Controller { return new(TokenController) }
// Builds an access token from credentials
func (tctl TokenController) Post(d api.Arguments) api.Response {
r := api.NewResponse()
/* (1) Init redis connection */
cli := db.Connect()
if cli == nil {
r.Err = e.Failure
return *r
}
/* (2) Extract api input */
role, err := d.GetString("role")
if err != nil {
r.Err = e.InvalidParam
r.Err.Put("url")
r.Err.Put(err.Error())
return *r
}
/* (3) Generate token */
hasher := sha512.New()
defer hasher.Reset()
hasher.Write([]byte(strconv.FormatInt(time.Now().Unix(), 5)))
token := hex.EncodeToString(hasher.Sum(nil))
/* (4) Store */
if !cli.Set(db.TOKEN, token, role, time.Minute) {
r.Err = e.Failure
return *r
}
r.Set("token", token)
r.Err = e.Success
return *r
}
func (tctl TokenController) Get(d api.Arguments) api.Response { return *api.NewResponse() }
func (tctl TokenController) Put(d api.Arguments) api.Response { return *api.NewResponse() }
func (tctl TokenController) Delete(d api.Arguments) api.Response { return *api.NewResponse() }