//用户登录 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": "/"}) } } }
// 登录;成功返回用户登录信息(user_login) func Login(username, passwd string) (*model.UserLogin, error) { userLogin := model.NewUserLogin() err := userLogin.Where("username="******" OR email=" + username).Find() if err != nil { logger.Errorf("用户 %s 登录错误:%s", username, err) return nil, errors.New("内部错误,请稍后再试!") } // 校验用户 if userLogin.Uid == 0 { logger.Infof("用户名 %s 不存在", username) return nil, ErrUsername } passcode := userLogin.GetPasscode() md5Passwd := util.Md5(passwd + passcode) logger.Debugf("passwd: %s, passcode: %s, md5passwd: %s, dbpasswd: %s", passwd, passcode, md5Passwd, userLogin.Passwd) if md5Passwd != userLogin.Passwd { logger.Infof("用户名 %s 填写的密码错误", username) return nil, ErrPasswd } // 登录,活跃度+1 go IncUserWeight("uid="+strconv.Itoa(userLogin.Uid), 1) return userLogin, nil }
//modify password func ChangePwd(email, newPwd string) (err error) { salt := util.RandString(8) pwd := util.Md5(salt + newPwd) model.UserC.Do(func(c *mgo.Collection) { err = c.Update(bson.M{"email": email}, bson.M{"$set": bson.M{"salt": salt, "password": pwd}}) }) return }
// 生成加密密码 func (this *UserLogin) GenMd5Passwd(origPwd string) string { if origPwd == "" { origPwd = this.Passwd } this.passcode = fmt.Sprintf("%x", rand.Int31()) // 密码经过md5(passwd+passcode)加密保存 this.Passwd = util.Md5(origPwd + this.passcode) return this.Passwd }
//create an user, with dup_key error for email or nickname. func AddUser(email, nickname, password string) error { salt := util.RandString(8) password = util.Md5(salt + password) u := &User{Id: bson.NewObjectId(), Email: email, NickName: nickname, Salt: salt, Password: password, CreateTime: time.Now()} var err error model.UserC.Do(func(c *mgo.Collection) { err = c.Insert(u) if err != nil && !mgo.IsDup(err) { model.ErrorLog(model.UserC, err, u) } }) return err }
"path/filepath" "strings" "time" "util" ) // 自定义模板函数 var funcMap = template.FuncMap{ // 获取gravatar头像 "gravatar": func(emailI interface{}, size uint16) string { email, ok := emailI.(string) if !ok { // TODO:给一个默认的? return "" } return fmt.Sprintf("http://www.gravatar.com/avatar/%s?s=%d", util.Md5(email), size) }, // 转为前端显示需要的时间格式 "formatTime": func(i interface{}) string { ctime, ok := i.(string) if !ok { return "" } t, _ := time.Parse("2006-01-02 15:04:05", ctime) return t.Format(time.RFC3339) + "+08:00" }, "substring": func(str string, length int, suffix string) string { if length >= len(str) { return str } utf8Str := util.NewString(str)
/* txcode := map[int]string{ 0: `买单已委托,<a href="/trade/index.php?a=delegation">查看结果</a>`, 2: `没有足够的人民币`, 10: `没有足够的比特币`, 16: `您需要登录才能继续`, 17: `没有权限`, 42: `该委托已经取消,不能修改`, 44: `交易价钱太低`, 56:`卖出价格不能低于限价的95%`} logger.Traceln(txcode[m.Code]) */ func (w *BitvcTrade) Login() bool { login_url := Config["bitvc_login_url"] email := Config["bitvc_email"] clear_password := Config["bitvc_password"] password := util.Md5(clear_password + "hi,pwd") /* function calc_password_security_score(t) { var e = 0; return t.length < 4 ? e : (t.length >= 8 && e++, t.length >= 10 && e++, /[a-z]/.test(t) && /[A-Z]/.test(t) && e++, /[0-9]/.test(t) && e++, /.[!,@,#,$,%,^,&,*,?,_,~, -,£,(,)]/.test(t) && e++, e) }*/ var pwd_security_score int if len(clear_password) < 4 { pwd_security_score = 0 } else if len(clear_password) >= 8 { pwd_security_score++ if len(clear_password) >= 10 { pwd_security_score++ } } //f**k正则,不玩了! reg := regexp.MustCompile(`[[:ascii:]]`) fmt.Printf("%q\n", reg.FindAllString(password, -1)) // ["H" " 世界!123 G" "."] str_pwd_security_score := fmt.Sprintf("%d", pwd_security_score) post_arg := url.Values{"email": {email}, "password": {password}, "backurl": {"/index/index"}, "pwd_security_score": {str_pwd_security_score}} //logger.Traceln(strings.NewReader(post_arg.Encode())) req, err := http.NewRequest("POST", login_url, strings.NewReader(post_arg.Encode())) if err != nil { logger.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Referer", Config["bitvc_base_url"]) req.Header.Add("Connection", "keep-alive") req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36") logger.Traceln(req) //jar := NewJar() jar, _ := cookiejar.New(nil) w.client = &http.Client{nil, nil, jar} //w.client = new(http.Client) resp, err := w.client.Do(req) if err != nil { logger.Fatal(err) } defer resp.Body.Close() logger.Tracef("Login resp StatusCode=%v", resp.StatusCode) logger.Tracef("Login resp=%v", resp) if resp.StatusCode == 200 { var body string contentEncoding := resp.Header.Get("Content-Encoding") logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding) switch contentEncoding { case "gzip": body = DumpGZIP(resp.Body) default: bodyByte, _ := ioutil.ReadAll(resp.Body) body = string(bodyByte) ioutil.WriteFile("login.html", bodyByte, os.ModeAppend) } logger.Traceln(resp.Header.Get("Content-Type")) ret := strings.Contains(body, "用户名或者密码错误") if ret { logger.Traceln("用户名或者密码错误") return false } w.isLogin = true return true } else if resp.StatusCode == 500 { w.isLogin = true return true } else { logger.Tracef("resp %v", resp) } return false }
/* txcode := map[int]string{ 0: `买单已委托,<a href="/trade/index.php?a=delegation">查看结果</a>`, 2: `没有足够的人民币`, 10: `没有足够的比特币`, 16: `您需要登录才能继续`, 17: `没有权限`, 42: `该委托已经取消,不能修改`, 44: `交易价钱太低`, 56:`卖出价格不能低于限价的95%`} logger.Traceln(txcode[m.Code]) */ func (w *BitvcTrade) Login() bool { fmt.Println("login....") login_url := Config["bitvc_login_url"] email := SecretOption["bitvc_email"] clear_password := SecretOption["bitvc_password"] password := util.Md5(clear_password + "hi,pwd") pwd_security_score := getPSS(clear_password) str_pwd_security_score := fmt.Sprintf("%d", pwd_security_score) post_arg := url.Values{"email": {email}, "password": {password}, "backurl": {"/index/index"}, "pwd_security_score": {str_pwd_security_score}} //logger.Traceln(strings.NewReader(post_arg.Encode())) req, err := http.NewRequest("POST", login_url, strings.NewReader(post_arg.Encode())) if err != nil { logger.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Referer", Config["bitvc_base_url"]) req.Header.Add("Connection", "keep-alive") req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36") logger.Infoln(req) //jar := NewJar() /* how to do compatible like c define? jar, _ := cookiejar.New(nil) fmt.Println("version:", runtime.Version()) if runtime.Version() != "go1.3" { w.client = &http.Client{nil, nil, jar} } else { w.client = &http.Client{nil, nil, jar, 10 * time.Second} } */ //w.client = new(http.Client) resp, err := w.client.Do(req) if err != nil { logger.Fatal(err) } defer resp.Body.Close() logger.Infof("Login resp StatusCode=%v", resp.StatusCode) logger.Infof("Login resp=%v", resp) if resp.StatusCode == 200 { var body string contentEncoding := resp.Header.Get("Content-Encoding") logger.Infof("HTTP returned Content-Encoding %s", contentEncoding) switch contentEncoding { case "gzip": body = DumpGZIP(resp.Body) default: bodyByte, _ := ioutil.ReadAll(resp.Body) body = string(bodyByte) ioutil.WriteFile("login.html", bodyByte, os.ModeAppend) } logger.Traceln(resp.Header.Get("Content-Type")) ret := strings.Contains(body, "用户名或者密码错误") if ret { logger.Traceln("用户名或者密码错误") return false } w.isLogin = true return true } else if resp.StatusCode == 500 { w.isLogin = true return true } else { logger.Infof("resp %v", resp) } return false }
// 生成 退订 邮件的 token func GenUnsubscribeToken(user *model.User) string { return util.Md5(user.String() + Config["unsubscribe_token_key"]) }