Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.54 KB | None | 0 0
  1. package controllers
  2.  
  3. import (
  4. "encoding/json"
  5. m "kocard/models"
  6. "kocard/services"
  7. s "kocard/services"
  8. "strings"
  9.  
  10. "github.com/astaxie/beego"
  11. "github.com/astaxie/beego/context"
  12. "github.com/astaxie/beego/orm"
  13. //"github.com/astaxie/beego/validation"
  14. //"github.com/dgrijalva/jwt-go"
  15. "github.com/astaxie/beego/validation"
  16. "github.com/dgrijalva/jwt-go"
  17. )
  18.  
  19. // AuthController operations for Auth
  20. type AuthController struct {
  21. beego.Controller
  22. }
  23.  
  24. type User struct {
  25. Email string `json:"email"`
  26. Password string `json:"password"`
  27. }
  28.  
  29. type UserAuth struct {
  30. Id int `json:"id"`
  31. Token string `json:"token"`
  32. }
  33.  
  34. type RegUser struct {
  35. Username string `json:"username"`
  36. Firstname string `json:"firstname"`
  37. Lastname string `json:"lastname"`
  38. Email string `json:"email"`
  39. Password string `json:"password"`
  40. Subscribe bool `json:"subscribe"`
  41. }
  42.  
  43. func (a *AuthController) responseWithError(status int, message map[string]string, err interface{}) {
  44. beego.Error(err)
  45.  
  46. a.Ctx.Output.SetStatus(status)
  47. a.Data["json"] = message
  48. a.ServeJSON()
  49. a.StopRun()
  50.  
  51. return
  52. }
  53.  
  54. func VerifyPassword(rawPwd, encodedPwd string) bool {
  55. // split
  56. var salt, encoded string
  57. salt = encodedPwd[:15]
  58. encoded = encodedPwd[16:]
  59.  
  60. return s.EncodePassword(rawPwd, salt) == encoded
  61. }
  62.  
  63. // API sign in (login)
  64. func (a *AuthController) SignIn() {
  65. //get body of request
  66. u := User{}
  67. json.Unmarshal(a.Ctx.Input.RequestBody, &u)
  68. //parse body
  69. if err := a.ParseForm(&u); err != nil {
  70. a.responseWithError(500, map[string]string{"message": err.Error()}, err)
  71.  
  72. return
  73. }
  74. //if pk is empty - return error
  75. if u.Email == "" {
  76. a.responseWithError(500, map[string]string{"message": "Empty email!"}, "Auth: empty email!")
  77.  
  78. return
  79. }
  80. if u.Password == "" {
  81. a.responseWithError(500, map[string]string{"message": "Empty password!"}, "Auth: empty password!")
  82.  
  83. return
  84. }
  85.  
  86. us := m.Users{}
  87.  
  88. o := orm.NewOrm()
  89. o.Using("default")
  90. //find user
  91. err := o.QueryTable("users").Filter("email", u.Email).Limit(1).One(&us)
  92.  
  93. if us.Active == false {
  94. a.responseWithError(403, map[string]string{"message": "Unauthorised access to this resource"}, "Auth: Unauthorised access to this resource")
  95.  
  96. return
  97. }
  98.  
  99. if err != nil {
  100. a.responseWithError(400, map[string]string{"message": err.Error()}, err)
  101.  
  102. return
  103. }
  104.  
  105. if VerifyPassword(u.Password, us.Passw) == false {
  106. a.responseWithError(401, map[string]string{"message": "Wrong password"}, "Auth: Wrong password")
  107.  
  108. return
  109. }
  110.  
  111. token, expiresIn, err := services.CreateSignedTokenString(us.Email)
  112. a.Data["json"] = map[string]interface{}{
  113. "auth_key": token,
  114. "expires_in": expiresIn,
  115. "role": us.Role,
  116. }
  117. a.ServeJSON()
  118. a.StopRun()
  119. }
  120.  
  121. // API sign up (registration)
  122. func (a *AuthController) SignUp() {
  123. r := RegUser{}
  124. json.Unmarshal(a.Ctx.Input.RequestBody, &r)
  125. //parse body
  126. if err := a.ParseForm(&r); err != nil {
  127. a.responseWithError(500, map[string]string{"message": err.Error()}, err)
  128.  
  129. return
  130. }
  131. // reg form validation
  132. valid := validation.Validation{}
  133. b, err := valid.Valid(&r)
  134.  
  135. if err != nil {
  136. }
  137. // if not valid - response with error
  138. if !b {
  139. for _, err := range valid.Errors {
  140. a.responseWithError(401, map[string]string{"message": err.Error()}, err)
  141. }
  142. return
  143. }
  144. // else register
  145. u := new(m.Users)
  146.  
  147. salt := s.GetRandomString(15)
  148. encodedPwd := salt + "$" + s.EncodePassword(r.Password, salt)
  149.  
  150. u.Alias = r.Username
  151. u.FirstName = r.Firstname
  152. u.LastName = r.Lastname
  153. u.Email = r.Email
  154. u.Passw = encodedPwd
  155. u.Role = 20
  156. u.Active = true
  157. u.NewCardsAlert = r.Subscribe
  158. u.Salt = salt
  159.  
  160. id, err := m.AddUser(u)
  161.  
  162. if err != nil {
  163. a.responseWithError(500, map[string]string{"message": err.Error()}, err)
  164.  
  165. return
  166. }
  167.  
  168. listAddress := "register_user@" + beego.AppConfig.String("MgDomain")
  169.  
  170. list, err := services.CreateMailingList(listAddress, "users", "add user after registration")
  171. beego.Info(list, err)
  172.  
  173. error := services.AddListMember(listAddress, u.Email, u.FirstName + " " + u.LastName)
  174. beego.Info(error)
  175.  
  176. w := new(m.Wallets)
  177. w.Alias = "ETH" + salt
  178. w.CurrencyId = 1
  179. w.UserId = int(id)
  180. w.Balance = 1000
  181. w.State = true
  182. _, err = m.AddWallets(w)
  183.  
  184. // return success
  185. a.Data["json"] = map[string]interface{}{
  186. "id": id,
  187. "success": true,
  188. }
  189. a.ServeJSON()
  190. a.StopRun()
  191. }
  192.  
  193. // customize filters for fine grain authorization
  194. var FilterUser = func(ctx *context.Context) {
  195. // Unauthorised requests
  196. 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") {
  197. return
  198. }
  199.  
  200. // Auth requests
  201. if strings.HasPrefix(ctx.Input.URL(), "/admin") && ctx.Input.Header("X-ACCESS-TOKEN") != "" {
  202. parsedToken, err := s.ParseTokenFromSignedTokenString(ctx.Input.Header("X-ACCESS-TOKEN"))
  203.  
  204. if err == nil && parsedToken.Valid {
  205. expiresIn := parsedToken.Claims.(jwt.MapClaims)["expiresIn"]
  206. email := parsedToken.Claims.(jwt.MapClaims)["email"]
  207.  
  208. ctx.Input.SetData("expiresIn", expiresIn)
  209. ctx.Input.SetData("email", email)
  210.  
  211. var u m.Users
  212. o := orm.NewOrm()
  213. o.Using("default")
  214. // find user
  215. err := o.QueryTable("users").Filter("email", email).Limit(1).One(&u)
  216.  
  217. if err == nil && u.Role == 0 {
  218. return
  219. } else {
  220. ctx.Output.SetStatus(403)
  221. ctx.Output.Body([]byte(`{"message": "Unauthorised access to this resource"}`))
  222. }
  223. }
  224. }
  225.  
  226. // rest api, that uses tokens
  227. if strings.HasPrefix(ctx.Input.URL(), "/api") && ctx.Input.Header("X-ACCESS-TOKEN") != "" {
  228. parsedToken, err := s.ParseTokenFromSignedTokenString(ctx.Input.Header("X-ACCESS-TOKEN"))
  229. if err == nil && parsedToken.Valid {
  230. email := parsedToken.Claims.(jwt.MapClaims)["email"]
  231. ctx.Input.SetData("email", email)
  232.  
  233. var u m.Users
  234. o := orm.NewOrm()
  235. o.Using("default")
  236. // find user
  237. err := o.QueryTable("users").Filter("email", email).Limit(1).One(&u)
  238.  
  239. if err == nil && u.Active == true {
  240. return
  241. } else {
  242. ctx.Output.SetStatus(403)
  243. ctx.Output.Body([]byte(`{"message": "Unauthorised access to this resource"}`))
  244. }
  245. }
  246. }
  247.  
  248. // delete before production
  249.  
  250. if strings.HasPrefix(ctx.Input.URL(), "/setnewpass") ||
  251. strings.HasPrefix(ctx.Input.URL(), "/newpassform") ||
  252. strings.HasPrefix(ctx.Input.URL(), "/forgpass") ||
  253. strings.HasPrefix(ctx.Input.URL(), "/setlastbl") ||
  254. strings.HasPrefix(ctx.Input.URL(), "/admwall") ||
  255. strings.HasPrefix(ctx.Input.URL(), "/registration") ||
  256. strings.HasPrefix(ctx.Input.URL(), "/invlist") ||
  257. strings.HasPrefix(ctx.Input.URL(), "/floortr") ||
  258. strings.HasPrefix(ctx.Input.URL(), "/cardtest") ||
  259. strings.HasPrefix(ctx.Input.URL(), "/cardmint") ||
  260. strings.HasPrefix(ctx.Input.URL(), "/cardminted") ||
  261. strings.HasPrefix(ctx.Input.URL(), "/deposit") ||
  262. strings.HasPrefix(ctx.Input.URL(), "/withdraw") ||
  263. strings.HasPrefix(ctx.Input.URL(), "/wdrwconf") ||
  264. strings.HasPrefix(ctx.Input.URL(), "/gettrad") ||
  265. strings.HasPrefix(ctx.Input.URL(), "/conftrad") ||
  266. strings.HasPrefix(ctx.Input.URL(), "/userpars") ||
  267. strings.HasPrefix(ctx.Input.URL(), "/trantest") ||
  268. strings.HasPrefix(ctx.Input.URL(), "/trantestd") ||
  269. strings.HasPrefix(ctx.Input.URL(), "/get-notifications") {
  270.  
  271. return
  272. }
  273.  
  274. ctx.Output.SetStatus(403)
  275. ctx.Output.Body([]byte(`{"message": "Unauthorised access to this resource"}`))
  276.  
  277. }
  278.  
  279. // API sign in with Two factor google auth (login)
  280. func (a *AuthController) SignInFirstStep() {
  281. //get body of request
  282. u := User{}
  283. json.Unmarshal(a.Ctx.Input.RequestBody, &u)
  284. //parse body
  285. if err := a.ParseForm(&u); err != nil {
  286. a.responseWithError(500, map[string]string{"message": err.Error()}, err)
  287.  
  288. return
  289. }
  290. //if pk is empty - return error
  291. if u.Email == "" {
  292. a.responseWithError(500, map[string]string{"message": "Empty email!"}, "Auth: empty email!")
  293.  
  294. return
  295. }
  296. if u.Password == "" {
  297. a.responseWithError(500, map[string]string{"message": "Empty password!"}, "Auth: empty password!")
  298.  
  299. return
  300. }
  301.  
  302. us := m.Users{}
  303.  
  304. o := orm.NewOrm()
  305. o.Using("default")
  306. //find user
  307. err := o.QueryTable("users").Filter("email", u.Email).Limit(1).One(&us)
  308.  
  309. if err != nil {
  310. a.responseWithError(400, map[string]string{"message": err.Error()}, err)
  311.  
  312. return
  313. }
  314.  
  315. if VerifyPassword(u.Password, us.Passw) == false {
  316. a.responseWithError(401, map[string]string{"message": "Wrong password"}, "Auth: Wrong password")
  317.  
  318. return
  319. }
  320. if us.TwoFactorAuth == true {
  321.  
  322. qrName, err := services.GenerateQrCode(us.Salt)
  323. if err != nil {
  324. a.responseWithError(401, map[string]string{"message": err.Error()}, err)
  325.  
  326. return
  327. }
  328. a.Data["json"] = map[string]interface{}{
  329. "user_id": us.Id,
  330. "qr_code": qrName,
  331. }
  332. }else{
  333.  
  334. token, expiresIn, err := services.CreateSignedTokenString(us.Email)
  335. if err != nil {
  336. a.responseWithError(400, map[string]string{"message": err.Error()}, err)
  337. }
  338. a.Data["json"] = map[string]interface{}{
  339. "auth_key": token,
  340. "expires_in": expiresIn,
  341. "id": us.Id,
  342. "role": us.Role,
  343. }
  344. }
  345.  
  346. a.ServeJSON()
  347. a.StopRun()
  348. }
  349.  
  350. // API sign in with Two factor google auth (login)
  351. func (a *AuthController) SignInSecondStep() {
  352. //get body of request
  353. u := UserAuth{}
  354. json.Unmarshal(a.Ctx.Input.RequestBody, &u)
  355. //parse body
  356. if err := a.ParseForm(&u); err != nil {
  357. a.responseWithError(500, map[string]string{"message": err.Error()}, err)
  358.  
  359. return
  360. }
  361. //if pk is empty - return error
  362. if u.Id == 0 {
  363. a.responseWithError(500, map[string]string{"message": "Empty Id!"}, "Auth: empty Id!")
  364.  
  365. return
  366. }
  367. if u.Token == "" {
  368. a.responseWithError(500, map[string]string{"message": "Empty Token!"}, "Auth: empty Token!")
  369.  
  370. return
  371. }
  372.  
  373. us := m.Users{}
  374.  
  375. o := orm.NewOrm()
  376. o.Using("default")
  377. //find user
  378. err := o.QueryTable("users").Filter("id", u.Id).Limit(1).One(&us)
  379.  
  380. if err != nil {
  381. a.responseWithError(400, map[string]string{"message": err.Error()}, err)
  382.  
  383. return
  384. }
  385. secret := services.GenerateSecretPhrase(us.Salt)
  386. status, err := services.ValidateToken(secret, u.Token)
  387.  
  388. if err != nil {
  389. a.responseWithError(400, map[string]string{"message": err.Error()}, err)
  390. }
  391.  
  392. if status == false {
  393. a.responseWithError(500, map[string]string{"message": "Wrong Token!"}, "Auth: wrong Token!")
  394. }
  395.  
  396. token, expiresIn, err := services.CreateSignedTokenString(us.Email)
  397. a.Data["json"] = map[string]interface{}{
  398. "auth_key": token,
  399. "expires_in": expiresIn,
  400. "id": us.Id,
  401. "role": us.Role,
  402. }
  403. a.ServeJSON()
  404. a.StopRun()
  405. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement