//用户登录 func (this *User) Login() { json := this.ReqJson() if json != nil { email := json.Get("email").MustString() password := json.Get("password").MustString() valid := validation.Validation{} valid.Email(email, "email") valid.MinSize(password, 6, "passwordMin") valid.MaxSize(password, 12, "passwordMax") if valid.HasErrors() { this.CustomAbort(enum.BadRequest.Code(), enum.BadRequest.Str()) } u := user.GetUserByEmail(email) if u == nil { //用户不存在 this.RespJson(enum.UserNotExist, nil) } else if util.Md5(u.Salt+password) != u.Password { //密码错误 this.RespJson(enum.PasswordIncorrect, nil) } else { this.SetSession("uId", u.Id.Hex()) user.SetToken(u.Id, this.StartSession().SessionID()) //using cookie as token this.RespJson(enum.OK, map[string]interface{}{"url": "/"}) } } }
// Valid user add func (u *User) ValidUserAdd() *validation.Validation { valid := validation.Validation{} u.Username = strings.TrimSpace(u.Username) u.Password = strings.TrimSpace(u.Password) valid.Required(u.Username, "UsernameReq").Message("用户名不能为空") valid.MinSize(u.Username, 6, "UsernameMixSize").Message("用户名不能小于6个字符") valid.MaxSize(u.Username, 10, "UsernameMaxSize").Message("用户姓名不能大于10个字符") valid.MinSize(u.Password, 6, "PasswordMinSize").Message("用户密码不能小于6为字符") valid.MaxSize(u.Password, 10, "PasswordMaxSize").Message("用户密码不能大于10个字符") // uLen := len(strings.TrimSpace(u.Username)) // if uLen < 6 || uLen > 10 { // valid.SetError("Username", "用户不能为空,长度大于6小于10") // } // pLen := len(strings.TrimSpace(u.Password)) // if pLen < 6 || pLen > 10 { // valid.SetError("Password", "用户密码不能为空,长度大于6小于10") // } return &valid }
//用户注册 func (this *User) Register() { req := this.ReqJson() if req != nil { email := req.Get("email").MustString() nickName := req.Get("nickName").MustString() password := req.Get("password").MustString() valid := validation.Validation{} valid.Email(email, "email") valid.MinSize(nickName, 6, "nickNameMin") valid.MaxSize(nickName, 12, "nickNameMax") valid.MinSize(password, 6, "passwordMin") valid.MaxSize(password, 12, "passwordMax") if valid.HasErrors() { this.CustomAbort(enum.BadRequest.Code(), enum.BadRequest.Str()) } err := user.AddUser(email, nickName, password) if err == nil { this.RespJson(enum.OK, nil) } else { if strings.Contains(err.Error(), "email") { this.RespJson(enum.EmailAlreadyExist, nil) } else if strings.Contains(err.Error(), "nickname") { this.RespJson(enum.NickNameAlreadyExist, nil) } else { beego.Error(err) } } } }
func (this *UserController) Login() { if this.Ctx.Input.Method() == "GET" { if this.GetSession("user") != nil { this.Redirect("/", 302) } this.TplNames = "console/login.html" return } json := this.ReqJson() email := json.Get("email").MustString() password := json.Get("password").MustString() valid := validation.Validation{} valid.Email(email, "email") valid.MinSize(password, 6, "passwordMin") valid.MaxSize(password, 12, "passwordMax") if valid.HasErrors() { this.CustomAbort(enum.RespCode.BadRequest.Code(), enum.RespCode.BadRequest.Str()) } user := user.GetUserByEmail(email) if user == nil { //用户不存在 this.RespJson(enum.RespCode.UserNotExist, nil) } else if util.Md5(user.Salt+password) != user.Password { //密码错误 this.RespJson(enum.RespCode.PasswordIncorrect, nil) } else { this.SetSession("user", user) this.RespJson(enum.RespCode.OK, map[string]interface{}{"url": "/"}) } }
//注册 todo 错误处理的优雅封装 func (this *User) Register() { reqBody := this.Ctx.Input.RequestBody reqJson, err := simplejson.NewJson(reqBody) //非法请求 if err != nil { this.Abort("400") } email := reqJson.Get("email").MustString() nickname := reqJson.Get("nickname").MustString() password := reqJson.Get("password").MustString() valid := validation.Validation{} valid.Email(email, "email") //邮箱 valid.MinSize(nickname, 5, "nickname") //昵称至少5位 valid.MinSize(password, 6, "password") //密码至少6位 //非法请求 if valid.HasErrors() { this.Abort("400") } enumResult := user.AddUser(email, nickname, password) fmt.Println(enumResult) this.Data["json"] = map[string]interface{}{"code": enumResult, "msg": enumResult.String()} this.ServeJson() }
// 编辑管理员信息(新增或修改) func (this *Admins) Edit() { id := this.GetString(":id") o := models.NewAdmin() if id == this.CurrentAdmin.Id.Hex() { o = this.CurrentAdmin } else { if id != "" { if o1, err := o.Find(id); nil == err && nil != o1 { o = o1 } } } fm := models.AdminForm{} if err := this.ParseForm(&fm); err != nil { this.JsonOut(nil, "1", err.Error()) } valid := validation.Validation{} valid.Required(fm.UserName, "userName").Message("账号不能为空") valid.Required(fm.Email, "email").Message("邮箱不能为空") valid.Required(fm.RoleId, "roleId").Message("角色不能为空") valid.Required(fm.Status, "status").Message("状态不能为空") // 非新增 if o.Id.Valid() { if fm.PassWord != "" { valid.MinSize(fm.PassWord, 6, "passWord").Message("密码至少需要6位") } } else { valid.Required(fm.PassWord, "passWord").Message("密码不能为空") valid.MinSize(fm.PassWord, 6, "passWord").Message("密码至少需要6位") } if errmsg, ok := this.HasErrMsgs(valid); ok { this.JsonOut(nil, "1", errmsg) } o.UserName = fm.UserName o.Email = fm.Email o.RoleId = fm.RoleId o.Status = fm.Status if fm.PassWord != "" { o.PassWord = utils.Encrypt(fm.PassWord) } err := o.Persist() if nil == err { this.JsonOut(nil, "0") } else if o.Id.Valid() { this.JsonOut(nil, "1", "修改管理员失败") } else { this.JsonOut(nil, "1", "添加管理员失败") } }
// Valid cmdForm add func (this *Cmd) ValidCmdAdd() *validation.Validation { valid := validation.Validation{} valid.Required(this.Shell, "ShellReq").Message("脚本不能为空") valid.MinSize(this.Shell, 1, "ShellMixSize").Message("脚本不能小于1个字符") valid.MaxSize(this.Shell, 225, "ShellMaxSize").Message("脚本不能大于225个字符") valid.Required(this.AgentId, "AgentIdReq").Message("主机不能为空") return &valid }
func (this *MainController) Reset() { this.activeContent("user/reset") flash := beego.NewFlash() u := this.Ctx.Input.Param(":uuid") o := orm.NewOrm() o.Using("default") user := models.AuthUser{Reset_key: u} err := o.Read(&user, "Reset_key") if err == nil { if this.Ctx.Input.Method() == "POST" { password := this.GetString("password") password2 := this.GetString("password2") valid := validation.Validation{} valid.MinSize(password, 6, "password") valid.Required(password2, "password2") if valid.HasErrors() { errormap := make(map[string]string) for _, err := range valid.Errors { errormap[err.Key] = err.Message } this.Data["Errors"] = errormap return } if password != password2 { flash.Error("Passwords don't match") flash.Store(&this.Controller) return } h := pk.HashPassword(password) // Convert password hash to string user.Password = hex.EncodeToString(h.Hash) + hex.EncodeToString(h.Salt) user.Reset_key = "" if _, err := o.Update(&user); err != nil { flash.Error("Internal error") flash.Store(&this.Controller) return } flash.Notice("Password updated.") flash.Store(&this.Controller) this.Redirect("/notice", 302) } } else { flash.Notice("Invalid key.") flash.Store(&this.Controller) this.Redirect("/notice", 302) } }
// Valid userForm add func (a *Agent) ValidAgentAdd() *validation.Validation { valid := validation.Validation{} a.Host = strings.TrimSpace(a.Host) a.Port = strings.TrimSpace(a.Port) a.LoginName = strings.TrimSpace(a.LoginName) a.LoginPass = strings.TrimSpace(a.LoginPass) valid.Required(a.Host, "HostReq").Message("远程地址不能为空") valid.MinSize(a.Host, 10, "HostMixSize").Message("远程地址不能小于10个字符") valid.MaxSize(a.Host, 225, "HostMaxSize").Message("远程地址不能大于225个字符") valid.Required(a.Port, "PortReq").Message("端口不能为空") valid.MinSize(a.Port, 2, "PortMixSize").Message("端口不能小于2个字符") valid.MaxSize(a.Port, 6, "PortMaxSize").Message("端口不能大于6个字符") valid.Required(a.LoginName, "LoginNameReq").Message("登录用户名不能为空") valid.MinSize(a.LoginName, 1, "LoginNameMixSize").Message("登录用户名不能小于1个字符") valid.MaxSize(a.LoginName, 225, "LoginNameMaxSize").Message("登录用户名不能大于225个字符") valid.Required(a.LoginPass, "LoginPassReq").Message("登录密码不能为空") valid.MinSize(a.LoginPass, 1, "LoginPassMixSize").Message("登录密码不能小于1个字符") valid.MaxSize(a.LoginPass, 225, "LoginPassMaxSize").Message("登录密码不能大于225个字符") return &valid }
func (c *TUserController) ValidUserName() { username := c.GetString("username") valid := validation.Validation{} re, _ := regexp.Compile(`[\p{Han},\w]+`) valid.Match(username, re, "用户名") valid.MinSize(username, 4, "用户名") valid.MaxSize(username, 16, "用户名") if valid.HasErrors() { c.Data["json"] = map[string]string{"error": "用户名不正确"} } else { err := models.ValidUserName(username) if err == nil { c.Data["json"] = map[string]string{"error": "用户名已经存在"} } else { c.Data["json"] = map[string]string{"message": "你可以使用此用户名"} } } c.ServeJson() }
//登录 func (this *User) Login() { fmt.Println(this) reqBody := this.Ctx.Input.RequestBody fmt.Println(string(reqBody)) reqJson, err := simplejson.NewJson(reqBody) //非法请求 if err != nil { this.Abort("400") } fmt.Println(reqJson) email := reqJson.Get("email").MustString() password := reqJson.Get("password").MustString() valid := validation.Validation{} valid.Email(email, "email") valid.MinSize(password, 6, "password") //密码至少6位 //非法请求 if valid.HasErrors() { this.Abort("400") } fmt.Println(reqJson) if currentUser := user.FindUser(email); currentUser == nil { this.Data["json"] = map[string]interface{}{"code": enum.UserNotExist, "msg": enum.UserNotExist.String()} } else { if currentUser.Password != common.Md5(password+currentUser.Salt) { this.Data["json"] = map[string]interface{}{"code": enum.PasswordError, "msg": enum.PasswordError.String()} } else { this.Data["json"] = map[string]interface{}{"code": enum.OK, "msg": enum.OK.String()} //讲token写入cookie token := user.UpdateCookieToken(*currentUser) this.SetSession(this.Ctx.GetCookie("token"), token) } } this.ServeJson() }
func (this *UserController) Register() { if this.Ctx.Input.Method() == "GET" { if can, err := beego.AppConfig.Bool("CanBeRegister"); err == nil && can { this.Data["CanBeRegister"] = true } this.TplNames = "console/register.html" return } req := this.ReqJson() email := req.Get("email").MustString() nickName := req.Get("nickName").MustString() password := req.Get("password").MustString() valid := validation.Validation{} valid.Email(email, "email") valid.MinSize(nickName, 6, "nickNameMin") valid.MaxSize(nickName, 12, "nickNameMax") valid.MinSize(password, 6, "passwordMin") valid.MaxSize(password, 12, "passwordMax") if valid.HasErrors() { this.CustomAbort(enum.RespCode.BadRequest.Code(), enum.RespCode.BadRequest.Str()) } err := user.AddUser(email, nickName, password) if err == nil { this.RespJson(enum.RespCode.OK, nil) } else { if strings.Contains(err.Error(), "email") { this.RespJson(enum.RespCode.EmailExist, nil) } else if strings.Contains(err.Error(), "nick_name") { this.RespJson(enum.RespCode.NickNameExist, nil) } else { beego.Error(err) } } }
// Valid userForm add func (this *Server) ValidServerAdd() *validation.Validation { valid := validation.Validation{} valid.Required(this.Content, "ContentReq").Message("内容不能为空") valid.MinSize(this.Content, 1, "ContentMixSize").Message("内容不能小于1个字符") valid.Required(this.Theme, "ThemeReq").Message("配置主题不能为空") valid.MinSize(this.Theme, 1, "ThemeMixSize").Message("配置主题不能小于1个字符") valid.Required(this.UserId, "UserIdReq").Message("请登录") valid.MinSize(this.UserId, 1, "UserIdMixSize").Message("请登录") return &valid }
func (this *MainController) Register() { this.activeContent("user/register") if this.Ctx.Input.Method() == "POST" { flash := beego.NewFlash() first := this.GetString("first") last := this.GetString("last") email := this.GetString("email") username := this.GetString("username") password := this.GetString("password") password2 := this.GetString("password2") valid := validation.Validation{} valid.Required(first, "first") valid.Email(email, "email") valid.MinSize(password, 6, "password") valid.Required(password2, "password2") if valid.HasErrors() { errormap := []string{} for _, err := range valid.Errors { errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n") } this.Data["Errors"] = errormap return } if password != password2 { flash.Error("Passwords don't match") flash.Store(&this.Controller) return } h := pk.HashPassword(password) //******** Save user info to database o := orm.NewOrm() o.Using("default") user := models.AuthUser{First: first, Last: last, Username: username, Email: email} // Convert password hash to string user.Password = hex.EncodeToString(h.Hash) + hex.EncodeToString(h.Salt) // Add user to database with new uuid and send verification email u := uuid.NewV4() user.Reg_key = u.String() _, err := o.Insert(&user) if err != nil { flash.Error(email + " already registered") flash.Store(&this.Controller) return } if !sendVerification(email, u.String()) { flash.Error("Unable to send verification email") flash.Store(&this.Controller) return } flash.Notice("Your account has been created. You must verify the account in your email.") flash.Store(&this.Controller) this.Redirect("/notice", 302) } }
func (this *MainController) Profile() { this.activeContent("user/profile") //******** This page requires login sess := this.GetSession("acme") if sess == nil { this.Redirect("/user/login/home", 302) return } m := sess.(map[string]interface{}) flash := beego.NewFlash() //******** Read password hash from database var x pk.PasswordHash x.Hash = make([]byte, 32) x.Salt = make([]byte, 16) o := orm.NewOrm() o.Using("default") user := models.AuthUser{Username: m["username"].(string)} err := o.Read(&user, "Username") if err == nil { // scan in the password hash/salt if x.Hash, err = hex.DecodeString(user.Password[:64]); err != nil { fmt.Println("ERROR:", err) } if x.Salt, err = hex.DecodeString(user.Password[64:]); err != nil { fmt.Println("ERROR:", err) } } else { flash.Error("Internal error") flash.Store(&this.Controller) return } // Create an applist //Get all running apps url := "http://107.167.184.225:8080/v2/apps/" //bytestring := []byte(newstring) req, err := http.NewRequest("GET", url, nil) if err != nil { panic(err) } //Make the request res, err := http.DefaultClient.Do(req) if err != nil { panic(err) //Something is wrong while sending request } body, err := ioutil.ReadAll(res.Body) if err != nil { panic(err) } JSONSPLIT := strings.Split(string(body), strings.ToLower(user.Username)) numberOfApps := len(JSONSPLIT) - 1 //this.Data["AppList"] = string(body) appNames := make([]string, numberOfApps) fmt.Println("Number of apps for user: "******"' { break } appNames[i-1] = appNames[i-1] + string(JSONBYTES[j]) } fmt.Println(appNames[i-1]) } formstring := "" for i := 0; i < len(appNames); i++ { formstring = formstring + "<tr><td>" + appNames[i] + "</td>" formstring = formstring + "<td><a href='http://" + appNames[i] + ".klouds.org' target='_blank'> GO TO SITE</a></td>" formstring = formstring + "<td><a href='../deleteApp/" + appNames[i] + "'> DELETE APP </a></td>" } formstring = formstring + "</tr></table>" this.Data["AppList"] = formstring // this deferred function ensures that the correct fields from the database are displayed defer func(this *MainController, user *models.AuthUser) { this.Data["First"] = user.First this.Data["Last"] = user.Last this.Data["Username"] = user.Username this.Data["Email"] = user.Email }(this, &user) if this.Ctx.Input.Method() == "POST" { first := this.GetString("first") last := this.GetString("last") username := this.GetString("username") email := this.GetString("email") current := this.GetString("current") password := this.GetString("password") password2 := this.GetString("password2") valid := validation.Validation{} valid.Required(first, "first") valid.Email(email, "email") valid.Required(current, "current") if valid.HasErrors() { errormap := []string{} for _, err := range valid.Errors { errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n") } this.Data["Errors"] = errormap return } if password != "" { valid.MinSize(password, 6, "password") valid.Required(password2, "password2") if valid.HasErrors() { errormap := []string{} for _, err := range valid.Errors { errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n") } this.Data["Errors"] = errormap return } if password != password2 { flash.Error("Passwords don't match") flash.Store(&this.Controller) return } h := pk.HashPassword(password) // Convert password hash to string user.Password = hex.EncodeToString(h.Hash) + hex.EncodeToString(h.Salt) } //******** Compare submitted password with database if !pk.MatchPassword(current, &x) { flash.Error("Bad current password") flash.Store(&this.Controller) return } //******** Save user info to database user.First = first user.Last = last user.Username = username user.Email = email _, err := o.Update(&user) if err == nil { flash.Notice("Profile updated") flash.Store(&this.Controller) m["username"] = email } else { flash.Error("Internal error") flash.Store(&this.Controller) return } } }
func (this *MainController) Profile() { this.activeContent("user/profile") //******** This page requires login sess := this.GetSession("acme") if sess == nil { this.Redirect("/user/login/home", 302) return } m := sess.(map[string]interface{}) flash := beego.NewFlash() //******** Read password hash from database var x pk.PasswordHash x.Hash = make([]byte, 32) x.Salt = make([]byte, 16) o := orm.NewOrm() o.Using("default") user := models.AuthUser{Email: m["username"].(string)} err := o.Read(&user, "Email") if err == nil { // scan in the password hash/salt if x.Hash, err = hex.DecodeString(user.Password[:64]); err != nil { fmt.Println("ERROR:", err) } if x.Salt, err = hex.DecodeString(user.Password[64:]); err != nil { fmt.Println("ERROR:", err) } } else { flash.Error("Internal error") flash.Store(&this.Controller) return } if this.Ctx.Input.Method() == "POST" { u := user2{} if err := this.ParseForm(&u); err != nil { fmt.Println("cannot parse form") return } this.Data["User"] = u valid := validation.Validation{} if b, _ := valid.Valid(&u); !b { this.Data["Errors"] = valid.ErrorsMap return } password := this.GetString("password") password2 := this.GetString("password2") if password != "" { valid.MinSize(password, 6, "password") valid.Required(password2, "password2") if valid.HasErrors() { errormap := make(map[string]string) for _, err := range valid.Errors { errormap[err.Key] = err.Message } this.Data["Errors"] = errormap return } if password != password2 { flash.Error("Passwords don't match") flash.Store(&this.Controller) return } h := pk.HashPassword(password) // Convert password hash to string user.Password = hex.EncodeToString(h.Hash) + hex.EncodeToString(h.Salt) } //******** Compare submitted password with database if !pk.MatchPassword(u.Current, &x) { flash.Error("Bad current password") flash.Store(&this.Controller) return } //******** Save user info to database user.First = u.First user.Last = u.Last user.Email = u.Email _, err := o.Update(&user) if err == nil { flash.Notice("Profile updated") flash.Store(&this.Controller) m["username"] = u.Email } else { flash.Error("Internal error") flash.Store(&this.Controller) return } } else { this.Data["User"] = user } }