示例#1
0
文件: api.go 项目: cnhans/kingdoms
/* 测试战斗提交表单 */
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()
}
示例#2
0
func (conf *Config) ValidateCommonSpecs() bool {
	valid := validation.Validation{}

	//Validate mandatory fields.
	valid.Required(conf.configLinux.Version, "Version")
	//Version must complient with  SemVer v2.0.0
	valid.Match(conf.configLinux.Version, regexp.MustCompile("^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$"), "Version")
	valid.Required(conf.configLinux.Platform.OS, "OS")
	valid.Required(conf.configLinux.Platform.Arch, "Platform.Arch")

	for _, env := range conf.configLinux.Process.Env {
		//If Process defined, env cannot be empty
		valid.Required(env, "Process.Env")
	}
	valid.Required(conf.configLinux.Process.User.UID, "User.UID")
	valid.Required(conf.configLinux.Process.User.GID, "User.GID")
	valid.Required(conf.configLinux.Root.Path, "Root.Path")
	//Iterate over Mount array
	for _, mount := range conf.configLinux.Mounts {
		//If Mount points defined, it must define these three.
		valid.Required(mount.Type, "Mount.Type")
		valid.Required(mount.Source, "Mount.Source")
		valid.Required(mount.Destination, "Mount.Destination")
	}

	if valid.HasErrors() {
		// validation does not pass
		for i, err := range valid.Errors {
			fmt.Println(i, err.Key, err.Message)
		}
		return false
	}

	return true
}
示例#3
0
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()
}
示例#4
0
// PUT /api/user/pwd/:uid/
func ModifyPassword(ctx *macaron.Context, as rest.AuthService, ut *rest.UserToken) {
	// 1.0
	var mpwd rest.ModifyPasswordReq
	uid, ok := getUidAndBodyWithAuth(ctx, as, ut, rest.DummyOptId, &mpwd)
	if !ok {
		return
	}

	// 2.0
	u := &models.User{Id: uid}
	if err := u.ReadOneOnly("Salt", "Password"); err == orm.ErrNoRows {
		ctx.JSON(http.StatusNotFound, rest.INVALID_USER)
		return
	} else if err != nil {
		ctx.JSON(http.StatusInternalServerError, tkits.DB_ERROR)
		return
	}

	if !tkits.CmpPasswd(mpwd.OldPasswd, u.Salt, u.Password) {
		ctx.JSON(http.StatusNotFound, rest.INVALID_USER)
		return
	}

	valid := validation.Validation{}
	valid.Match(mpwd.NewPasswd, rest.ValidPasswd,
		"NewPasswd").Message(rest.PasswdPrompt)
	if !validMember(ctx, &valid) {
		return
	}

	// 3.0
	pwd, salt := tkits.GenPasswd(mpwd.NewPasswd, 8)
	u.Salt = salt
	u.Password = pwd
	u.Updated = time.Now()

	if row, _ := u.Update("Salt", "Password", "Updated"); row != 1 {
		ctx.JSON(http.StatusInternalServerError, tkits.DB_ERROR)
		return
	}

	ctx.Status(http.StatusOK)
}
示例#5
0
/* 文章界面 */
func (this *ArticleController) Article() {
	//是否用手机访问
	isMobile := IsMobile(this.Ctx.Input.UserAgent())

	//验证
	valid := validation.Validation{}
	valid.Match(this.Ctx.Input.Param(":id"), regexp.MustCompile("^[a-z0-9]+$"), "category")
	if valid.HasErrors() { //没有通过验证则返回首页
		this.Ctx.Redirect(302, this.UrlFor("IndexController.Index"))
		this.StopRun()
	}

	//寻找文章
	article := &models.Article{}
	ok := article.FindOne(this.Ctx.Input.Param(":id"))
	if !ok { //文章不存在
		this.Ctx.Redirect(302, this.UrlFor("IndexController.Index"))
		this.StopRun()
	}
	this.Data["article"] = article

	//根据文章存储的分类id查询分类信息
	category := &models.Category{}
	category.FindOne(article.Category)
	this.Data["category"] = category

	//根据分类信息查询父分类信息以及自己分类的文章(必定存在父级分类)
	parent, articles, hots := category.FindParentAndArticles()
	this.Data["parent"] = parent
	this.Data["articles"] = articles
	this.Data["hots"] = hots

	if isMobile { //如果是手机访问
		this.TplNames = "mobile/article/article.html"
	} else {
		this.TplNames = "article/article.html"
	}
	this.Render()
}
示例#6
0
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
}
示例#7
0
func (c *UserController) Register() {
	// get
	c.setupView("user/register")
	if c.Ctx.Input.Method() == "POST" {

		flash := beego.NewFlash()
		valid := validation.Validation{}

		firstname := c.GetString("firstname")
		lastname := c.GetString("lastname")
		username := c.GetString("username")
		email := c.GetString("email")
		password := c.GetString("password")
		passwordConfirm := c.GetString("password_confirm")

		// password validation
		valid.Required(passwordConfirm, "password_confirm")
		r, err := regexp.Compile(strings.Join([]string{"^", password, "$"}, ""))
		if err != nil {
			fmt.Printf("There is a problem with your regexp.")
			return
		}
		valid.Match(passwordConfirm, r, "password_confirm")

		config := uuid.StateSaverConfig{SaveReport: true, SaveSchedule: 30 * time.Minute}
		uuid.SetupFileSystemStateSaver(config)
		u1 := uuid.NewV4()

		user := &models.AuthUser{
			Firstname: firstname,
			Lastname:  lastname,
			Username:  username,
			Email:     email,
			Password:  password,
			Reg_key:   u1.String(),
		}

		b, err := valid.Valid(user)
		if err != nil {
			fmt.Println(err)
		}
		if !b {
			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
			fmt.Println(errormap)
			return
		}

		hash, hashErr := bcrypt.GenerateFromPassword([]byte(password), 1)
		if hashErr != nil {
			c.Abort("401")
		}
		user.Password = string(hash)

		o := orm.NewOrm()
		o.Using("default")

		if created, id, err := o.ReadOrCreate(user, "Username"); err == nil {
			if created {
				fmt.Println("New user registered. Id:", id)
				flash.Notice("Welcome, " + username + "!")
				flash.Store(&c.Controller)

				link := "http://*****:*****@mail.com", "Start Go")
				msg.SetHeader("To", email)
				msg.SetHeader("Subject", "Account Verification for Start Go")
				msg.SetBody("text/html", "To verify your account, please click on the link: <a href=\""+link+"\">"+link+"</a>")
				m := gomail.NewMailer(host, "youremail@mail", "yourpassword", port)

				if errMail := m.Send(msg); errMail != nil {
					fmt.Println("Email was not sent!")
					fmt.Println(errMail)
				}

				return
			} else {
				flash.Error("Invalid data!")
				flash.Store(&c.Controller)
				errormap := []string{}
				errormap = append(errormap, "User already exist")
				c.Data["Errors"] = errormap
				return
			}
		}
	}
}
示例#8
0
文件: user_add.go 项目: wcreate/wuc
// POST /api/user/signup
func AddUser(ctx *macaron.Context, as rest.AuthService, cpt *captcha.Captcha) {
	var uar rest.UserAddReq
	ok := getBody(ctx, &uar)
	if !ok {
		return
	}

	log.Debugf("retrive CaptchaId = %s, CaptchaValue= %s", uar.CaptchaId, uar.CaptchaValue)
	if !cpt.Verify(uar.CaptchaId, uar.CaptchaValue) {
		ctx.JSON(http.StatusBadRequest, rest.INVALID_CAPTCHA)
		return
	}

	valid := validation.Validation{}
	valid.Email(uar.Email, "Email")
	valid.Match(uar.Username, rest.ValidPasswd,
		"Username").Message(rest.UsernamePrompt)
	valid.Match(uar.Passwd, rest.ValidPasswd,
		"Passwd").Message(rest.PasswdPrompt)
	if !validMember(ctx, &valid) {
		return
	}

	// check user whether existed
	u := &models.User{}
	if err := u.Find(uar.Email, uar.Username, ""); err != orm.ErrNoRows {
		ctx.JSON(http.StatusBadRequest, rest.INVALID_SIGNUP)
		return
	}

	// check reserve users
	if _, ok := rest.ReserveUsers[uar.Username]; ok {
		ctx.JSON(http.StatusBadRequest, rest.INVALID_SIGNUP)
		return
	}

	// generate password mask
	pwd, salt := tkits.GenPasswd(uar.Passwd, 8)
	u.Salt = salt
	u.Password = pwd
	u.Updated = time.Now()
	u.Username = uar.Username
	u.Email = uar.Email
	if id, err := u.Insert(); err != nil {
		ctx.JSON(http.StatusInternalServerError, tkits.DB_ERROR)
		return
	} else {
		u.Id = id
	}

	// generate a token
	if token, err := as.GenUserToken(ctx.RemoteAddr(), u.Id, 15, rest.TokenUser); err != nil {
		ctx.JSON(http.StatusInternalServerError, tkits.SYS_ERROR)
		return
	} else {
		rsp := &rest.UserAddRsp{u.Id, u.Username, token}

		// set some cookies
		if uar.CookieMaxAge == 0 {
			uar.CookieMaxAge = 60 * 60 * 12 //half of one day
		}

		suid := fmt.Sprintf("%v", u.Id)
		ctx.SetCookie("token", token, uar.CookieMaxAge)
		ctx.SetCookie("uid", suid, uar.CookieMaxAge)

		ctx.JSON(http.StatusOK, rsp)
	}
}