// 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 *LoginController) Login() { val := validation.Validation{} username := this.GetString("username") password := this.GetString("password") val.Required(username, "username") val.Required(password, "password") if val.HasErrors() { for _, v := range val.Errors { this.Ctx.WriteString("<script>alert('" + v.Key + " " + v.Message + "');</script>") //遇到一个错误就可以StopRun了其实,这里只是练习验证模块 } this.StopRun() } toolbox.Display("u", username) toolbox.Display("pa", password) password = utils.LoginPassword(password) toolbox.Display("paaa", password) if user.CheckLogin(username, password) == true { this.SetSession("username", username) this.Ctx.SetCookie("username", username) this.Redirect("/admin", 302) } else { this.Redirect("/login", 302) } }
func (this *AdminController) EditUser() { o := orm.NewOrm() o.Using("default") usersId, _ := strconv.Atoi(this.Ctx.Input.Param(":id")) users := models.User{} flash := beego.NewFlash() err := o.QueryTable("user").Filter("id", usersId).One(&users) if err != orm.ErrNoRows { err := this.ParseForm(&users) if err != nil { beego.Error("Impossible de parser. Raison: ", err) } else { valid := validation.Validation{} valid.Required(users.Mail, "mail") valid.Required(users.Role, "role") isValid, _ := valid.Valid(users) if this.Ctx.Input.Method() == "POST" { if !isValid { flash.Error("Impossible de mettre à jour l'utilisateur") flash.Store(&this.Controller) this.Redirect("/incident-manager/admin/user", 302) } else { _, err := o.Update(&users) if err == nil { flash.Notice("Utilisateur " + users.Mail + " mis à jour") flash.Store(&this.Controller) this.Redirect("/incident-manager/admin/user", 302) } else { fmt.Println("erreur") beego.Debug("Mise à jour Impossible dû a : ", err) } } } } this.Redirect("/incident-manager/admin/user", 302) } else { flash.Notice("Utilisateur %d n'existe pas", usersId) flash.Store(&this.Controller) this.Redirect("/incident-manager/", 302) } }
/* 测试战斗提交表单 */ func (this *ApiController) TestPost() { //测试提交的表单 valid := validation.Validation{} valid.Required(this.GetString("my"), "1") valid.Match(this.GetString("my"), regexp.MustCompile("^[,0-9]+$"), "2") valid.Required(this.GetString("enemie"), "3") valid.Match(this.GetString("enemie"), regexp.MustCompile("^[,0-9]+$"), "4") if valid.HasErrors() { //没有通过验证则退出 return } //解析提交的敌我方数据 myArray := strings.Split(this.GetString("my"), ",") enemieArray := strings.Split(this.GetString("enemie"), ",") mySlice := make([]string, len(myArray)) enemieSlice := make([]string, len(enemieArray)) for k, v := range myArray { mySlice[k] = v + ",0,0,0,0,0" } for k, v := range enemieArray { enemieSlice[k] = v + ",0,0,0,0,0" } //模拟战斗 index := IndexController{} result := index.SimulateFight(mySlice, "0;0", enemieSlice, "0;0") this.Data["json"] = result this.ServeJson() }
/** * 登录接收 */ func (this *UserController) Signup() { //errmsg := make(map[string]string) requestEmail := this.GetString("email") requestPassword := this.GetString("password") svalid := validation.Validation{} svalid.Required(requestEmail, "email") svalid.MaxSize(requestEmail, 40, "email") svalid.Required(requestPassword, "password") if svalid.HasErrors() { for _, err := range svalid.Errors { //fmt.Println(err.Key, err.Message) this.showmsg("Error Message", "["+err.Key+"]"+err.Message) } } var user models.User user.Email = requestEmail user.Password = models.Md5([]byte(requestPassword)) var Ru models.ReturnUser Ru = user.Select() if Ru.Id > 0 { this.SetSession("nickname", Ru.Nickname) this.SetSession("email", Ru.Email) this.SetSession("isadmin", Ru.Isadmin) this.Redirect("/", 302) } else { this.showmsg("Error", "Email OR Password IS WRONG") } }
func (this *Article) Validators(validator *validation.Validation, scenario string) { if scenario == "create" || scenario == "update" { validator.Required(this.Description, "description") validator.Min(this.Description, 0, "description") validator.Max(this.Description, 12000, "description") validator.Max(this.Title, 3, "title") validator.Min(this.Title, 255, "title") } }
func (this *RegisterController) Register() { o := orm.NewOrm() o.Using("default") register := models.Register{} flash := beego.NewFlash() // this.Data["Form"] = ®ister if err := this.ParseForm(®ister); err != nil { beego.Error("Couldn't parse the form. Reason: ", err) } else { valid := validation.Validation{} valid.Required(register.Mail, "mail") isValid, _ := valid.Valid(register) if this.Ctx.Input.Method() == "POST" { if !isValid { this.Data["errors"] = valid.ErrorsMap for _, err := range valid.Errors { beego.Error(err.Key, err.Message) } } else { r := this.Ctx.Input register.IP = r.IP() fmt.Println(register.IP) _, err := o.Insert(®ister) // res, err := o.Raw("INSERT INTO `incident` (`cat`, `title`, `description`,`date_request`, `priority`, `user_id`) VALUES (?,?,?,?,?,?)", register.Cat, register.Title, register.Description, date, register.Priority, this.GetSession("uid")).Exec() if err == nil { err := admin.SendMailAdmin() if err != nil { fmt.Println(err) } flash.Success(register.Mail + " : votre demande a bien été envoyé ") flash.Store(&this.Controller) this.Redirect("/", 302) } else { flash.Warning("Attention car cette adresse mail : " + register.Mail + " est déjà dans les demandes. ") flash.Store(&this.Controller) beego.Debug("Couldn't insert in tableName Register. Reason: ", err) } } } } Template(this, "user", "register", "Demande de Connexion / Nouveau mot de passe") }
// 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 ValidCompany(m *BCompany) string { v := validation.Validation{} v.Required(m.Name, "name").Message("单位名称不能为空") v.Required(m.Phone, "phone").Message("电话不能为空") v.Required(m.Address, "address").Message("地址不能为空") if v.HasErrors() { // 如果有错误信息,证明验证没通过 return utils.WrapErrors(v.Errors) } return "" }
//表单验证 func ValidUser(m *BUser) string { v := validation.Validation{} v.Required(m.Username, "username").Message("邮箱不能为空") v.Required(m.Password, "password").Message("密码不能为空") v.Email(m.Username, "username").Message("邮箱格式不正确") if v.HasErrors() { // 如果有错误信息,证明验证没通过 return utils.WrapErrors(v.Errors) } return "" }
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 *UserController) Login() { c.setupView("auth/login") if c.Ctx.Input.Method() == "POST" { flash := beego.NewFlash() username := c.GetString("username") password := c.GetString("password") valid := validation.Validation{} valid.Required(username, "username") valid.Required(password, "password") if valid.HasErrors() { errormap := []string{} for _, err := range valid.Errors { errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n") } flash.Error("Invalid data!") flash.Store(&c.Controller) c.Data["Errors"] = errormap return } o := orm.NewOrm() o.Using("default") user := &models.AuthUser{ Username: username, } err := o.Read(user, "Username") if err == orm.ErrNoRows { flash.Error("User not found!") flash.Store(&c.Controller) return } bcryptErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) if bcryptErr != nil { flash.Error("Wrong password!") flash.Store(&c.Controller) return } m := make(map[string]interface{}) m["email"] = user.Email m["username"] = user.Username m["fullname"] = user.Firstname + " " + user.Lastname m["timestamp"] = time.Now() c.SetSession("user", m) c.Redirect("/nladmin"+c.Ctx.Input.Param(":id"), 302) // go to previous page after login } }
func Create(post Post) (p Post, err error) { o := orm.NewOrm() valid := validation.Validation{} valid.Required(post.Title, "title") if valid.HasErrors() { // validation does not pass // print invalid message return p, errors.New("hshshshs") } id, err := o.Insert(&post) if err == nil { fmt.Println(id) } return post, nil }
func AddCategory(c Category) (Category, error) { o := orm.NewOrm() valid := validation.Validation{} valid.Required(c.Name, "name") if valid.HasErrors() { return c, errors.New("Error") } id, err := o.Insert(&c) if err == nil { fmt.Println(id) } else { fmt.Println(err) } return c, nil }
//编辑用户 func (this *UserController) Edit() { id, _ := this.GetInt("id") user := models.User{Id: id} if err := user.Read(); err != nil { this.showmsg("用户不存在") } errmsg := make(map[string]string) if this.Ctx.Request.Method == "POST" { password := strings.TrimSpace(this.GetString("password")) password2 := strings.TrimSpace(this.GetString("password2")) email := strings.TrimSpace(this.GetString("email")) active, _ := this.GetInt("active") valid := validation.Validation{} if password != "" { if v := valid.Required(password2, "password2"); !v.Ok { errmsg["password2"] = "请再次输入密码" } else if password != password2 { errmsg["password2"] = "两次输入的密码不一致" } else { user.Password = models.Md5([]byte(password)) } } if v := valid.Required(email, "email"); !v.Ok { errmsg["email"] = "请输入email地址" } else if v := valid.Email(email, "email"); !v.Ok { errmsg["email"] = "Email无效" } else { user.Email = email } if active > 0 { user.Active = 1 } else { user.Active = 0 } if len(errmsg) == 0 { user.Update() this.Redirect("/admin/user/list", 302) } } this.Data["errmsg"] = errmsg this.Data["user"] = user this.display() }
// 编辑管理员信息(新增或修改) 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", "添加管理员失败") } }
// We will check if the user data are valid func (u User) Valid() bool { v := validation.Validation{} v.Required(u.Name, "name") v.MaxSize(u.Name, 20, "nameMax") v.Required(u.Pass, "pass") v.MaxSize(u.Pass, 30, "passMax") v.Email(u.Email, "email") if v.HasErrors() { for _, e := range v.Errors { log.Println("Check valid user data:", e) } return false } return true }
func (this *IndexController) Add() { o := orm.NewOrm() o.Using("default") incidents := models.Incident{} flash := beego.NewFlash() // this.Data["Form"] = &incidents if err := this.ParseForm(&incidents); err != nil { beego.Error("Couldn't parse the form. Reason: ", err) } else { valid := validation.Validation{} valid.Required(incidents.Title, "title") valid.Required(incidents.Cat, "cat") valid.Required(incidents.Description, "description") valid.Required(incidents.DateRequest, "dateRequest") valid.Required(incidents.Priority, "priority") t := incidents.DateRequest date := t.Format("2006-01-02 15:04:05") isValid, _ := valid.Valid(incidents) if this.Ctx.Input.Method() == "POST" { if !isValid { this.Data["errors"] = valid.ErrorsMap for _, err := range valid.Errors { beego.Error(err.Key, err.Message) } } else { // _, err := o.Insert(&incidents) res, err := o.Raw("INSERT INTO `incident` (`cat`, `title`, `description`,`date_request`, `priority`, `user_id`) VALUES (?,?,?,?,?,?)", incidents.Cat, incidents.Title, incidents.Description, date, incidents.Priority, this.GetSession("uid")).Exec() if err == nil { num, _ := res.RowsAffected() fmt.Println("mysql row affected nums: ", num) flash.Notice("Incident " + incidents.Title + " added") flash.Store(&this.Controller) this.Redirect("/incident-manager/", 302) } else { beego.Debug("Couldn't insert new incident. Reason: ", err) } } } this.Data["dateRequest"] = time.Now() Template(this, "user", "declaration.tpl", "Déclarer un incident") } // defer this.DestroySession() }
func (conf *Config) ValidateLinuxSpecs() bool { valid := validation.Validation{} for _, namespace := range conf.configLinux.Linux.Namespaces { valid.Required(namespace.Type, "Namespace.Type") } if valid.HasErrors() { // validation does not pass fmt.Println("\nLinux Specific config errors\n") for i, err := range valid.Errors { fmt.Println(i, err.Key, err.Message) } return false } return true }
func main() { u := User{"man", 14} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") // valid.Range(u.Age, 0, 18, "age") // if valid.HasErrors() { // for _, err := range valid.Errors { // log.Println(err.Key, err.Message) // } // } // if v := valid.Max(u.Age, 140, "age"); !v.Ok { // log.Println(v.Error.Key, v.Error.Message) // } minAge := 18 valid.Min(u.Age, minAge, "age").Message("少儿不宜!") // 错误信息格式化 valid.Min(u.Age, minAge, "age").Message("%d不禁", minAge) }
func (this *Sites) Edit() { id := this.GetString(":id") fm := models.SiteForm{} if err := this.ParseForm(&fm); err != nil { this.JsonOut(nil, "1", err.Error()) } valid := validation.Validation{} valid.Required(fm.Name, "name").Message("名称不能为空") valid.Required(fm.Link, "link").Message("网址不能为空") valid.Required(fm.Status, "status").Message("状态不能为空") if errmsg, ok := this.HasErrMsgs(valid); ok { this.JsonOut(nil, "1", errmsg) } o := models.NewSite() if "" != id { o, _ = o.Find(id) } o.Name = fm.Name o.Link = fm.Link o.Desc = fm.Desc o.Status = fm.Status 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 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 }
/** * 注册逻辑处理 * @param {[type]} this *UserController) Join( [description] * @return {[type]} [description] */ func (this *UserController) Join() { beego.AutoRender = false errmsg := make(map[string]string) requestEmail := this.GetString("email") requestNickname := this.GetString("nickname") requestPassword := this.GetString("password") jvalid := validation.Validation{} jvalid.Required(requestEmail, "email") jvalid.MaxSize(requestEmail, 40, "email") jvalid.Required(requestNickname, "nickname") jvalid.MaxSize(requestNickname, 20, "nickname") jvalid.Required(requestPassword, "password") fmt.Println(jvalid.HasErrors()) if jvalid.HasErrors() { for _, err := range jvalid.Errors { //fmt.Println(err.Key, err.Message) this.showmsg("Error Message", "["+err.Key+"]"+err.Message) } } if len(errmsg) == 0 { var user models.User user.Email = requestEmail user.Nickname = requestNickname user.Password = models.Md5([]byte(requestPassword)) user.Lastlogin = time.Now().Unix() if err := user.Insert(); err != nil { this.Ctx.WriteString(err.Error()) } } this.SetSession("nickname", requestNickname) this.SetSession("email", requestEmail) this.SetSession("isadmin", 0) this.Redirect("/", 302) }
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) Remove() { this.activeContent("user/remove") //******** This page requires login sess := this.GetSession("acme") if sess == nil { this.Redirect("/user/login/home", 302) return } m := sess.(map[string]interface{}) if this.Ctx.Input.Method() == "POST" { current := this.GetString("current") valid := validation.Validation{} 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 } 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 } //******** Compare submitted password with database if !pk.MatchPassword(current, &x) { flash.Error("Bad current password") flash.Store(&this.Controller) return } //******** Delete user record _, err = o.Delete(&user) if err == nil { flash.Notice("Your account is deleted.") flash.Store(&this.Controller) this.DelSession("acme") this.Redirect("/notice", 302) } 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{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) Login() { this.activeContent("user/login") back := strings.Replace(this.Ctx.Input.Param(":back"), ">", "/", -1) // allow for deeper URL such as l1/l2/l3 represented by l1>l2>l3 fmt.Println("back is", back) if this.Ctx.Input.Method() == "POST" { flash := beego.NewFlash() username := this.GetString("username") password := this.GetString("password") valid := validation.Validation{} valid.Required(password, "password") 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 } fmt.Println("Authorization is", username, ":", password) //******** 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: username} err := o.Read(&user, "username") if err == nil { if user.Reg_key != "" { flash.Error("Account not verified") flash.Store(&this.Controller) return } // scan in the password hash/salt fmt.Println("Password to scan:", user.Password) 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) } fmt.Println("decoded password is", x) } else { flash.Error("No such user") flash.Store(&this.Controller) return } //******** Compare submitted password with database if !pk.MatchPassword(password, &x) { flash.Error("Bad password") flash.Store(&this.Controller) return } //******** Create session and go back to previous page m := make(map[string]interface{}) m["first"] = user.First m["username"] = username m["timestamp"] = time.Now() this.SetSession("acme", m) this.Redirect("/"+back, 302) } }
//添加用户 func (this *UserController) Add() { input := make(map[string]string) errmsg := make(map[string]string) if this.Ctx.Request.Method == "POST" { username := strings.TrimSpace(this.GetString("username")) password := strings.TrimSpace(this.GetString("password")) password2 := strings.TrimSpace(this.GetString("password2")) email := strings.TrimSpace(this.GetString("email")) active, _ := this.GetInt("active") input["username"] = username input["password"] = password input["password2"] = password2 input["email"] = email valid := validation.Validation{} if v := valid.Required(username, "username"); !v.Ok { errmsg["username"] = "******" } else if v := valid.MaxSize(username, 15, "username"); !v.Ok { errmsg["username"] = "******" } if v := valid.Required(password, "password"); !v.Ok { errmsg["password"] = "******" } if v := valid.Required(password2, "password2"); !v.Ok { errmsg["password2"] = "请再次输入密码" } else if password != password2 { errmsg["password2"] = "两次输入的密码不一致" } if v := valid.Required(email, "email"); !v.Ok { errmsg["email"] = "请输入email地址" } else if v := valid.Email(email, "email"); !v.Ok { errmsg["email"] = "Email无效" } if active > 0 { active = 1 } else { active = 0 } if len(errmsg) == 0 { var user models.User user.Username = username user.Password = models.Md5([]byte(password)) user.Email = email user.Active = int8(active) if err := user.Insert(); err != nil { this.showmsg(err.Error()) } this.Redirect("/admin/user/list", 302) } } this.Data["input"] = input this.Data["errmsg"] = errmsg this.display() }
func (p *Plugin) validateConfigSpecs(path string) bool { valid := validation.Validation{} data, err := ioutil.ReadFile(path) if err != nil { return false } json.Unmarshal(data, &p.config) //Validate mandatory fields. if result := valid.Required(p.config.Version, "Version"); !result.Ok { p.errorLog = append(p.errorLog, "Version cannot be empty") } //Version must complient with SemVer v2.0.0 if result := valid.Match(p.config.Version, regexp.MustCompile("^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$"), "Version"); !result.Ok { p.errorLog = append(p.errorLog, "Version must be in format of X.X.X (complient to Semver v2.0.0)") } if result := valid.Required(p.config.Platform.OS, "OS"); !result.Ok { p.errorLog = append(p.errorLog, "OS can be not empty") } if result := valid.Required(p.config.Platform.Arch, "Platform.Arch"); !result.Ok { p.errorLog = append(p.errorLog, "Platform.Arch is empty") } for _, env := range p.config.Process.Env { //If Process defined, env cannot be empty if result := valid.Required(env, "Process.Env"); !result.Ok { p.errorLog = append(p.errorLog, "Atleast one Process.Env is empty") break } } if result := valid.Required(p.config.Root.Path, "Root.Path"); !result.Ok { p.errorLog = append(p.errorLog, "Root.Path is empty") } //Iterate over Mount array for _, mount := range p.config.Mounts { //If Mount points defined, it must define these three. if result := valid.Required(mount.Source, "Mount.Source"); !result.Ok { p.errorLog = append(p.errorLog, "Atleast one Mount.Source is empty") break } if result := valid.Required(mount.Destination, "Mount.Destination"); !result.Ok { p.errorLog = append(p.errorLog, "Atleast one Mount.Destination is empty") break } } //Iterate over Mount array for _, mount := range p.config.Mounts { //If Mount points defined, it must define these three. if result := valid.Required(mount.Type, "Mount.Type"); !result.Ok { p.errorLog = append(p.errorLog, "Atleast one Mount.Type is empty") break } if result := valid.Required(mount.Source, "Mount.Source"); !result.Ok { p.errorLog = append(p.errorLog, "Atleast one Mount.Source is empty") break } } // Hooks Prestart for _, hook := range p.config.Hooks.Prestart { if result := valid.Required(hook.Path, "Hooks.Path"); !result.Ok { p.errorLog = append(p.errorLog, "Prestart hook Path cannot be empty") break } } // Hooks Poststop for _, hook := range p.config.Hooks.Poststop { if result := valid.Required(hook.Path, "Hooks.Path"); !result.Ok { p.errorLog = append(p.errorLog, "Poststop hook Path cannot be empty") break } } // UIDMappings mapping check. for _, uid := range p.config.Linux.UIDMappings { if result := valid.Range(uid.HostID, 0, 2147483647, "IDMapping.HostID"); !result.Ok { p.errorLog = append(p.errorLog, "UIDMapping's HostID must be valid integer") break } if result := valid.Range(uid.ContainerID, 0, 2147483647, "IDMapping.ContainerID"); !result.Ok { p.errorLog = append(p.errorLog, "UIDMapping's ContainerID must be valid integer") break } if result := valid.Range(uid.Size, 0, 2147483647, "IDMapping.Size"); !result.Ok { p.errorLog = append(p.errorLog, "UIDMapping's Size must be valid integer") break } } // GIDMappings mapping check. for _, gid := range p.config.Linux.GIDMappings { if result := valid.Range(gid.HostID, 0, 2147483647, "IDMapping.HostID"); !result.Ok { p.errorLog = append(p.errorLog, "GIDMapping's HostID must be valid integer") break } if result := valid.Range(gid.ContainerID, 0, 2147483647, "IDMapping.ContainerID"); !result.Ok { p.errorLog = append(p.errorLog, "GIDMapping's ContainerID must be valid integer") break } if result := valid.Range(gid.Size, 0, 2147483647, "IDMapping.Size"); !result.Ok { p.errorLog = append(p.errorLog, "GIDMapping's Size must be valid integer") break } } //TODO: CHeck Capablities. return true }