Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package controllers
- import (
- "encoding/json"
- m "kocard/models"
- "kocard/services"
- s "kocard/services"
- "strings"
- "github.com/astaxie/beego"
- "github.com/astaxie/beego/context"
- "github.com/astaxie/beego/orm"
- //"github.com/astaxie/beego/validation"
- //"github.com/dgrijalva/jwt-go"
- "github.com/astaxie/beego/validation"
- "github.com/dgrijalva/jwt-go"
- )
- // AuthController operations for Auth
- type AuthController struct {
- beego.Controller
- }
- type User struct {
- Email string `json:"email"`
- Password string `json:"password"`
- }
- type UserAuth struct {
- Id int `json:"id"`
- Token string `json:"token"`
- }
- type RegUser struct {
- Username string `json:"username"`
- Firstname string `json:"firstname"`
- Lastname string `json:"lastname"`
- Email string `json:"email"`
- Password string `json:"password"`
- Subscribe bool `json:"subscribe"`
- }
- func (a *AuthController) responseWithError(status int, message map[string]string, err interface{}) {
- beego.Error(err)
- a.Ctx.Output.SetStatus(status)
- a.Data["json"] = message
- a.ServeJSON()
- a.StopRun()
- return
- }
- func VerifyPassword(rawPwd, encodedPwd string) bool {
- // split
- var salt, encoded string
- salt = encodedPwd[:15]
- encoded = encodedPwd[16:]
- return s.EncodePassword(rawPwd, salt) == encoded
- }
- // API sign in (login)
- func (a *AuthController) SignIn() {
- //get body of request
- u := User{}
- json.Unmarshal(a.Ctx.Input.RequestBody, &u)
- //parse body
- if err := a.ParseForm(&u); err != nil {
- a.responseWithError(500, map[string]string{"message": err.Error()}, err)
- return
- }
- //if pk is empty - return error
- if u.Email == "" {
- a.responseWithError(500, map[string]string{"message": "Empty email!"}, "Auth: empty email!")
- return
- }
- if u.Password == "" {
- a.responseWithError(500, map[string]string{"message": "Empty password!"}, "Auth: empty password!")
- return
- }
- us := m.Users{}
- o := orm.NewOrm()
- o.Using("default")
- //find user
- err := o.QueryTable("users").Filter("email", u.Email).Limit(1).One(&us)
- if us.Active == false {
- a.responseWithError(403, map[string]string{"message": "Unauthorised access to this resource"}, "Auth: Unauthorised access to this resource")
- return
- }
- if err != nil {
- a.responseWithError(400, map[string]string{"message": err.Error()}, err)
- return
- }
- if VerifyPassword(u.Password, us.Passw) == false {
- a.responseWithError(401, map[string]string{"message": "Wrong password"}, "Auth: Wrong password")
- return
- }
- token, expiresIn, err := services.CreateSignedTokenString(us.Email)
- a.Data["json"] = map[string]interface{}{
- "auth_key": token,
- "expires_in": expiresIn,
- "role": us.Role,
- }
- a.ServeJSON()
- a.StopRun()
- }
- // API sign up (registration)
- func (a *AuthController) SignUp() {
- r := RegUser{}
- json.Unmarshal(a.Ctx.Input.RequestBody, &r)
- //parse body
- if err := a.ParseForm(&r); err != nil {
- a.responseWithError(500, map[string]string{"message": err.Error()}, err)
- return
- }
- // reg form validation
- valid := validation.Validation{}
- b, err := valid.Valid(&r)
- if err != nil {
- }
- // if not valid - response with error
- if !b {
- for _, err := range valid.Errors {
- a.responseWithError(401, map[string]string{"message": err.Error()}, err)
- }
- return
- }
- // else register
- u := new(m.Users)
- salt := s.GetRandomString(15)
- encodedPwd := salt + "$" + s.EncodePassword(r.Password, salt)
- u.Alias = r.Username
- u.FirstName = r.Firstname
- u.LastName = r.Lastname
- u.Email = r.Email
- u.Passw = encodedPwd
- u.Role = 20
- u.Active = true
- u.NewCardsAlert = r.Subscribe
- u.Salt = salt
- id, err := m.AddUser(u)
- if err != nil {
- a.responseWithError(500, map[string]string{"message": err.Error()}, err)
- return
- }
- listAddress := "register_user@" + beego.AppConfig.String("MgDomain")
- list, err := services.CreateMailingList(listAddress, "users", "add user after registration")
- beego.Info(list, err)
- error := services.AddListMember(listAddress, u.Email, u.FirstName + " " + u.LastName)
- beego.Info(error)
- w := new(m.Wallets)
- w.Alias = "ETH" + salt
- w.CurrencyId = 1
- w.UserId = int(id)
- w.Balance = 1000
- w.State = true
- _, err = m.AddWallets(w)
- // return success
- a.Data["json"] = map[string]interface{}{
- "id": id,
- "success": true,
- }
- a.ServeJSON()
- a.StopRun()
- }
- // customize filters for fine grain authorization
- var FilterUser = func(ctx *context.Context) {
- // Unauthorised requests
- if strings.HasPrefix(ctx.Input.URL(), "/login") || strings.HasPrefix(ctx.Input.URL(), "/register") || strings.HasPrefix(ctx.Input.URL(), "/add-message") || strings.HasPrefix(ctx.Input.URL(), "/add-sign-up-email") {
- return
- }
- // Auth requests
- if strings.HasPrefix(ctx.Input.URL(), "/admin") && ctx.Input.Header("X-ACCESS-TOKEN") != "" {
- parsedToken, err := s.ParseTokenFromSignedTokenString(ctx.Input.Header("X-ACCESS-TOKEN"))
- if err == nil && parsedToken.Valid {
- expiresIn := parsedToken.Claims.(jwt.MapClaims)["expiresIn"]
- email := parsedToken.Claims.(jwt.MapClaims)["email"]
- ctx.Input.SetData("expiresIn", expiresIn)
- ctx.Input.SetData("email", email)
- var u m.Users
- o := orm.NewOrm()
- o.Using("default")
- // find user
- err := o.QueryTable("users").Filter("email", email).Limit(1).One(&u)
- if err == nil && u.Role == 0 {
- return
- } else {
- ctx.Output.SetStatus(403)
- ctx.Output.Body([]byte(`{"message": "Unauthorised access to this resource"}`))
- }
- }
- }
- // rest api, that uses tokens
- if strings.HasPrefix(ctx.Input.URL(), "/api") && ctx.Input.Header("X-ACCESS-TOKEN") != "" {
- parsedToken, err := s.ParseTokenFromSignedTokenString(ctx.Input.Header("X-ACCESS-TOKEN"))
- if err == nil && parsedToken.Valid {
- email := parsedToken.Claims.(jwt.MapClaims)["email"]
- ctx.Input.SetData("email", email)
- var u m.Users
- o := orm.NewOrm()
- o.Using("default")
- // find user
- err := o.QueryTable("users").Filter("email", email).Limit(1).One(&u)
- if err == nil && u.Active == true {
- return
- } else {
- ctx.Output.SetStatus(403)
- ctx.Output.Body([]byte(`{"message": "Unauthorised access to this resource"}`))
- }
- }
- }
- // delete before production
- if strings.HasPrefix(ctx.Input.URL(), "/setnewpass") ||
- strings.HasPrefix(ctx.Input.URL(), "/newpassform") ||
- strings.HasPrefix(ctx.Input.URL(), "/forgpass") ||
- strings.HasPrefix(ctx.Input.URL(), "/setlastbl") ||
- strings.HasPrefix(ctx.Input.URL(), "/admwall") ||
- strings.HasPrefix(ctx.Input.URL(), "/registration") ||
- strings.HasPrefix(ctx.Input.URL(), "/invlist") ||
- strings.HasPrefix(ctx.Input.URL(), "/floortr") ||
- strings.HasPrefix(ctx.Input.URL(), "/cardtest") ||
- strings.HasPrefix(ctx.Input.URL(), "/cardmint") ||
- strings.HasPrefix(ctx.Input.URL(), "/cardminted") ||
- strings.HasPrefix(ctx.Input.URL(), "/deposit") ||
- strings.HasPrefix(ctx.Input.URL(), "/withdraw") ||
- strings.HasPrefix(ctx.Input.URL(), "/wdrwconf") ||
- strings.HasPrefix(ctx.Input.URL(), "/gettrad") ||
- strings.HasPrefix(ctx.Input.URL(), "/conftrad") ||
- strings.HasPrefix(ctx.Input.URL(), "/userpars") ||
- strings.HasPrefix(ctx.Input.URL(), "/trantest") ||
- strings.HasPrefix(ctx.Input.URL(), "/trantestd") ||
- strings.HasPrefix(ctx.Input.URL(), "/get-notifications") {
- return
- }
- ctx.Output.SetStatus(403)
- ctx.Output.Body([]byte(`{"message": "Unauthorised access to this resource"}`))
- }
- // API sign in with Two factor google auth (login)
- func (a *AuthController) SignInFirstStep() {
- //get body of request
- u := User{}
- json.Unmarshal(a.Ctx.Input.RequestBody, &u)
- //parse body
- if err := a.ParseForm(&u); err != nil {
- a.responseWithError(500, map[string]string{"message": err.Error()}, err)
- return
- }
- //if pk is empty - return error
- if u.Email == "" {
- a.responseWithError(500, map[string]string{"message": "Empty email!"}, "Auth: empty email!")
- return
- }
- if u.Password == "" {
- a.responseWithError(500, map[string]string{"message": "Empty password!"}, "Auth: empty password!")
- return
- }
- us := m.Users{}
- o := orm.NewOrm()
- o.Using("default")
- //find user
- err := o.QueryTable("users").Filter("email", u.Email).Limit(1).One(&us)
- if err != nil {
- a.responseWithError(400, map[string]string{"message": err.Error()}, err)
- return
- }
- if VerifyPassword(u.Password, us.Passw) == false {
- a.responseWithError(401, map[string]string{"message": "Wrong password"}, "Auth: Wrong password")
- return
- }
- if us.TwoFactorAuth == true {
- qrName, err := services.GenerateQrCode(us.Salt)
- if err != nil {
- a.responseWithError(401, map[string]string{"message": err.Error()}, err)
- return
- }
- a.Data["json"] = map[string]interface{}{
- "user_id": us.Id,
- "qr_code": qrName,
- }
- }else{
- token, expiresIn, err := services.CreateSignedTokenString(us.Email)
- if err != nil {
- a.responseWithError(400, map[string]string{"message": err.Error()}, err)
- }
- a.Data["json"] = map[string]interface{}{
- "auth_key": token,
- "expires_in": expiresIn,
- "id": us.Id,
- "role": us.Role,
- }
- }
- a.ServeJSON()
- a.StopRun()
- }
- // API sign in with Two factor google auth (login)
- func (a *AuthController) SignInSecondStep() {
- //get body of request
- u := UserAuth{}
- json.Unmarshal(a.Ctx.Input.RequestBody, &u)
- //parse body
- if err := a.ParseForm(&u); err != nil {
- a.responseWithError(500, map[string]string{"message": err.Error()}, err)
- return
- }
- //if pk is empty - return error
- if u.Id == 0 {
- a.responseWithError(500, map[string]string{"message": "Empty Id!"}, "Auth: empty Id!")
- return
- }
- if u.Token == "" {
- a.responseWithError(500, map[string]string{"message": "Empty Token!"}, "Auth: empty Token!")
- return
- }
- us := m.Users{}
- o := orm.NewOrm()
- o.Using("default")
- //find user
- err := o.QueryTable("users").Filter("id", u.Id).Limit(1).One(&us)
- if err != nil {
- a.responseWithError(400, map[string]string{"message": err.Error()}, err)
- return
- }
- secret := services.GenerateSecretPhrase(us.Salt)
- status, err := services.ValidateToken(secret, u.Token)
- if err != nil {
- a.responseWithError(400, map[string]string{"message": err.Error()}, err)
- }
- if status == false {
- a.responseWithError(500, map[string]string{"message": "Wrong Token!"}, "Auth: wrong Token!")
- }
- token, expiresIn, err := services.CreateSignedTokenString(us.Email)
- a.Data["json"] = map[string]interface{}{
- "auth_key": token,
- "expires_in": expiresIn,
- "id": us.Id,
- "role": us.Role,
- }
- a.ServeJSON()
- a.StopRun()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement