示例#1
0
func newAddrHandler(r *http.Request, w http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account) {

	wal, err := getWallet(user.Wallet.Id, user.Wallet.Key)
	if err != nil {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.DbError, err.Error()))
		return
	}
	k, err := wal.GenKey("")
	if err != nil {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.DbError, err.Error()))
		return
	}
	wal.AddKey(k)
	if _, err = saveWallet(user.Wallet.Id, wal); err != nil {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.DbError, err.Error()))
		return
	}

	user.Wallet.Addrs = append(user.Wallet.Addrs, k.PubKey)
	if err = user.AddWalletAddr(k.PubKey); err != nil {
		writeResponse(r.RequestURI, w, nil, err)
		return
	}

	writeResponse(r.RequestURI, w, k, nil)
}
示例#2
0
func consumeCoin(fromAddr string, value int64) (string, error) {
	if fromAddr == "" || value <= 0 {
		return "", nil
	}

	user := &models.Account{}
	if find, _ := user.FindByWalletAddr(fromAddr); !find {
		return "", errors.NewError(errors.NotFoundError)
	}
	wal, err := getWallet(user.Wallet.Id, user.Wallet.Key)
	if err != nil {
		return "", err
	}
	outputs, amount, err := getUnspent(fromAddr, wal.Keys, value)
	if value > amount {
		return "", errors.NewError(errors.AccessError, "余额不足")
	}
	changeAddr := fromAddr
	if len(changeAddr) == 0 {
		changeAddr = wal.Keys[0].PubKey
	}
	rawtx, err := CreateRawTx2(outputs, amount, value, WalletAddr, changeAddr)
	if err != nil {
		return "", err
	}
	return sendRawTx(rawtx)
}
示例#3
0
func loginHandlerV2(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, form loginFormV2) {
	user := &models.Account{}
	if exists, _ := models.CheckUserExists(form.Id, form.Type); !exists {
		writeResponse(request.RequestURI, resp,
			nil, errors.NewError(errors.AuthError, "该用户还未注册"))
		return
	}
	user.FindPass(form.Id, form.Type, Md5(form.Password))
	if len(user.Id) == 0 {
		writeResponse(request.RequestURI, resp,
			nil, errors.NewError(errors.AuthError))
		return
	}

	if user.TimeLimit < 0 {
		writeResponse(request.RequestURI, resp,
			nil, errors.NewError(errors.AuthError, "账户已禁用"))
		return
	}

	token := Uuid() + "-" + strconv.FormatInt(time.Now().AddDate(0, 0, 30).Unix(), 10)
	redis.SetOnlineUser(token, user.Id)

	data := map[string]interface{}{
		"access_token": token,
		"userid":       user.Id,
		//"last_login_time": user.LastLogin.Unix(),
	}
	writeResponse(request.RequestURI, resp, data, nil)
}
示例#4
0
func regHandlerV2(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, form regFormV2) {

	exists, err := models.CheckUserExists(form.Id, form.Type)
	if err != nil {
		writeResponse(request.RequestURI, resp,
			nil, errors.NewError(errors.DbError))
		return
	}
	if exists {
		writeResponse(request.RequestURI, resp,
			nil, errors.NewError(errors.UserExistError))
		return
	}

	dbw, err := getNewWallet()
	if err != nil {
		writeResponse(request.RequestURI, resp,
			nil, errors.NewError(errors.DbError, "创建钱包失败"))
		return
	}

	user := &models.Account{
		Role:     form.Type,
		Password: Md5(form.Password),
		Nickname: form.Nickname,
		Profile:  form.Profile,
		Gender:   form.Gender,
		Birth:    form.Birthday,
		Wallet:   *dbw,
		RegTime:  time.Now(),
	}

	switch form.Type {
	case models.AccountPhone:
		user.Phone = form.Id
	case models.AccountWeibo:
		user.Weibo = form.Id
	case models.AccountEmail:
		fallthrough
	default:
		user.Email = form.Id
	}

	if err := user.Save(); err != nil {
		writeResponse(request.RequestURI, resp, nil, err)
		return
	}

	token := Uuid() + "-" + strconv.FormatInt(time.Now().AddDate(0, 0, 30).Unix(), 10)
	data := map[string]string{"access_token": token, "userid": user.Id}
	writeResponse(request.RequestURI, resp, data, nil)

	redis.LogRegister(user.Id, form.Type)
	redis.SetOnlineUser(token, user.Id)

	// ws push
	//regNotice(user.Id, redis)
}
示例#5
0
func (this *Article) Save() error {
	this.Id = bson.NewObjectId()
	if len(this.Parent) == 0 {
		if err := save(articleColl, this, true); err != nil {
			return errors.NewError(errors.DbError, err.Error())
		}
		return nil
	}

	if !bson.IsObjectIdHex(this.Parent) {
		return errors.NewError(errors.InvalidMsgError)
	}

	update := bson.M{
		"$push": bson.M{
			"reviews": this.Id.Hex(),
		},
		"$inc": bson.M{
			"review_count": 1,
		},
	}
	if this.Type == ArticleCoach {
		update = bson.M{
			"$addToSet": bson.M{
				"coaches": this.Author,
			},
			"$inc": bson.M{
				"coach_review_count": 1,
			},
		}
	}

	f := func(c *mgo.Collection) error {
		runner := txn.NewRunner(c)
		ops := []txn.Op{
			{
				C:      articleColl,
				Id:     this.Id,
				Assert: txn.DocMissing,
				Insert: this,
			},
			{
				C:      articleColl,
				Id:     bson.ObjectIdHex(this.Parent),
				Assert: txn.DocExists,
				Update: update,
			},
		}

		return runner.Run(ops, bson.NewObjectId(), nil)
	}

	if err := withCollection("comment_tx", &mgo.Safe{}, f); err != nil {
		log.Println(err)
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}
示例#6
0
func (this *Article) Remove() error {
	find, err := this.findOne(bson.M{"author": this.Author, "_id": this.Id})
	if !find {
		return err
	}

	if len(this.Parent) == 0 {
		if err := removeId(articleColl, this.Id, true); err != nil {
			if e, ok := err.(*mgo.LastError); ok {
				return errors.NewError(errors.DbError, e.Error())
			}
		}
		return nil
	}

	update := bson.M{
		"$pull": bson.M{
			"reviews": this.Id.Hex(),
		},
		"$inc": bson.M{
			"review_count": -1,
		},
	}
	if this.Type == ArticleCoach {
		update = bson.M{
			"$inc": bson.M{
				"coach_review_count": -1,
			},
		}
	}

	f := func(c *mgo.Collection) error {
		runner := txn.NewRunner(c)
		ops := []txn.Op{
			{
				C:      articleColl,
				Id:     this.Id,
				Remove: true,
			},
			{
				C:      articleColl,
				Id:     bson.ObjectIdHex(this.Parent),
				Update: update,
			},
		}

		return runner.Run(ops, bson.NewObjectId(), nil)
	}
	if err := withCollection("comment_tx", &mgo.Safe{}, f); err != nil {
		log.Println(err)
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}
示例#7
0
func (this *Article) Comments(typ string, paging *Paging, withoutContent bool) (int, []Article, error) {
	var articles []Article
	total := 0

	sortFields := []string{"-pub_time"}

	var selector bson.M

	if withoutContent {
		selector = bson.M{"content": 0, "contents": 0}
	}

	query := bson.M{
		"parent": this.Id.Hex(),
	}
	switch typ {
	case ArticleCoach:
		query["type"] = typ
	default:
		query["type"] = bson.M{
			"$ne": ArticleCoach,
		}
	}

	if err := psearch(articleColl, query, selector,
		sortFields, &total, &articles, articlePagingFunc, paging); err != nil {
		e := errors.NewError(errors.DbError, err.Error())
		if err == mgo.ErrNotFound {
			e = errors.NewError(errors.NotFoundError, err.Error())
		}
		return total, nil, e
	}

	for i := 0; i < len(articles); i++ {
		if articles[i].Id.Hex() == paging.First {
			articles = articles[:i]
			break
		} else if articles[i].Id.Hex() == paging.Last {
			articles = articles[i+1:]
			break
		}
	}

	paging.First = ""
	paging.Last = ""
	paging.Count = 0
	if len(articles) > 0 {
		paging.First = articles[0].Id.Hex()
		paging.Last = articles[len(articles)-1].Id.Hex()
		paging.Count = total
	}

	return total, articles, nil
}
示例#8
0
func GetArticles(tag string, paging *Paging, withoutContent bool) (int, []Article, error) {
	var articles []Article
	total := 0

	query := bson.M{
		"parent": nil,
	}
	if len(tag) > 0 {
		query["tags"] = tag
	}

	var selector bson.M

	if withoutContent {
		selector = bson.M{
			"content":  0,
			"contents": 0,
		}
	}

	sortFields := []string{"-pub_time", "-_id"}

	if err := psearch(articleColl, query, selector,
		sortFields, nil, &articles, articlePagingFunc, paging); err != nil {
		e := errors.NewError(errors.DbError, err.Error())
		if err == mgo.ErrNotFound {
			e = errors.NewError(errors.NotFoundError, err.Error())
		}
		return total, nil, e
	}

	for i := 0; i < len(articles); i++ {
		if articles[i].Id.Hex() == paging.First {
			articles = articles[:i]
			break
		} else if articles[i].Id.Hex() == paging.Last {
			articles = articles[i+1:]
			break
		}
	}

	paging.First = ""
	paging.Last = ""
	paging.Count = 0
	if len(articles) > 0 {
		paging.First = articles[0].Id.Hex()
		paging.Last = articles[len(articles)-1].Id.Hex()
		paging.Count = total
	}

	return total, articles, nil
}
示例#9
0
func resetPasswdHandler(r *http.Request, w http.ResponseWriter,
	form resetPasswdForm) {
	user := &models.Account{}
	if b, err := user.FindByPhone(form.Phone); !b {
		e := errors.NewError(errors.NotExistsError, "未绑定手机,无法重置密码")
		if err != nil {
			e = errors.NewError(errors.DbError)
		}
		writeResponse(r.RequestURI, w, nil, e)
		return
	}

	err := user.SetPassword(Md5(form.Password))
	writeResponse(r.RequestURI, w, nil, err)
}
示例#10
0
func (this *Account) SetAuthInfo(types string, images []string, desc string) error {
	var change bson.M

	authInfo := &AuthInfo{Images: images, Desc: desc, Status: AuthVerifying}

	switch types {
	case AuthIdCard:
		change = bson.M{
			"$set": bson.M{"auth.idcardtmp": authInfo},
		}
	case AuthCert:
		change = bson.M{
			"$set": bson.M{"auth.certtmp": authInfo},
		}
	case AuthRecord:
		change = bson.M{
			"$set": bson.M{"auth.recordtmp": authInfo},
		}
	default:
		return nil
	}

	if err := updateId(accountColl, this.Id, change, true); err != nil {
		return errors.NewError(errors.DbError)
	}

	return nil
}
示例#11
0
func (article *Article) Update() error {
	m := bson.M{}

	if len(article.Author) > 0 {
		m["author"] = article.Author
	}
	if len(article.Contents) > 0 {
		m["contents"] = article.Contents
	}
	if len(article.Tags) > 0 {
		m["tags"] = article.Tags
	}
	if article.PubTime.Unix() > 0 {
		m["pub_time"] = article.PubTime
	}

	change := bson.M{
		"$set": m,
	}

	if err := updateId(articleColl, article.Id, change, true); err != nil {
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}
示例#12
0
func (this *Article) SetThumb(userid string, thumb bool) error {

	var m bson.M

	if thumb {
		m = bson.M{
			"$addToSet": bson.M{
				"thumbs": userid,
			},
			"$inc": bson.M{
				"thumb_count": 1,
			},
		}
	} else {
		m = bson.M{
			"$pull": bson.M{
				"thumbs": userid,
			},
			"$inc": bson.M{
				"thumb_count": -1,
			},
		}
	}

	if err := updateId(articleColl, this.Id, m, true); err != nil {
		return errors.NewError(errors.DbError)
	}

	return nil
}
示例#13
0
func (this *Article) Exists() (bool, error) {
	b, err := exists(articleColl, bson.M{"_id": this.Id})
	if err != nil {
		return false, errors.NewError(errors.DbError)
	}
	return b, nil
}
示例#14
0
func userInfoHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, p Parameter) {
	user := &models.Account{}
	form := p.(getInfoForm)
	if find, err := user.FindByUserid(form.Userid); !find {
		if err == nil {
			err = errors.NewError(errors.NotExistsError)
		}
		writeResponse(request.RequestURI, resp, nil, err)
		return
	}

	info := convertUser(user, redis)
	//info.Pet = userPet(info.Props.Level)
	info.ScoreRank, _ = user.PropIndex("score", user.Props.Score)

	if uid := redis.OnlineUser(p.TokenId()); len(uid) > 0 {
		relation := redis.Relationship(uid, user.Id)
		switch relation {
		case models.RelFriend:
			info.Relation = "FRIENDS"
		case models.RelFollowing:
			info.Relation = "ATTENTION"
		case models.RelFollower:
			info.Relation = "FANS"
		case models.RelBlacklist:
			info.Relation = "DEFRIEND"
		}
	}

	writeResponse(request.RequestURI, resp, info, nil)
}
示例#15
0
文件: tx.go 项目: shevilangle/sports
func (this *Tx) Save() error {
	this.Id = bson.NewObjectId()
	if err := save(txColl, this, true); err != nil {
		return errors.NewError(errors.DbError)
	}
	return nil
}
示例#16
0
/*
func (this *Account) GetTasks() (TaskList, error) {
	_, err := this.FindByUserid(this.Id)
	return this.Tasks, err
}

func (this *Account) AddTask(typ string, tid int, proofs []string) error {
	selector := bson.M{
		"_id": this.Id,
	}

	update(accountColl, selector, bson.M{"$pull": bson.M{"tasks.proofs": bson.M{"tid": tid}}}, true)

	var change bson.M
	if typ == TaskRunning {
		change = bson.M{
			"$pull": bson.M{
				"tasks.uncompleted": tid,
			},
			"$addToSet": bson.M{
				"tasks.waited": tid,
				"tasks.proofs": Proof{Tid: tid, Pics: proofs},
			},
			"$set": bson.M{
				"tasks.last": time.Now(),
			},
			"$inc": bson.M{
				"tasks.count": 1,
			},
		}
	} else {
		change = bson.M{
			"$addToSet": bson.M{
				"tasks.completed": tid,
			},
			"$set": bson.M{
				"tasks.last": time.Now(),
			},
		}
	}

	if err := update(accountColl, selector, change, true); err != nil {
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}

func (this *Account) SetTaskComplete(tid int, completed bool, reason string) error {
	if len(reason) > 0 {
		selector := bson.M{
			"_id":              this.Id,
			"tasks.proofs.tid": tid,
		}
		update(accountColl, selector, bson.M{"$set": bson.M{"tasks.proofs.$.result": reason}}, true)
	}

	selector := bson.M{
		"_id": this.Id,
	}
	var change bson.M

	if completed {
		change = bson.M{
			"$pull": bson.M{
				"tasks.waited": tid,
			},
			"$addToSet": bson.M{
				"tasks.completed": tid,
			},
			"$inc": bson.M{
				"tasks.count": -1,
			},
		}
	} else {
		change = bson.M{
			"$pull": bson.M{
				"tasks.waited": tid,
			},
			"$addToSet": bson.M{
				"tasks.uncompleted": tid,
			},
			"$inc": bson.M{
				"tasks.count": -1,
			},
		}
	}

	if err := update(accountColl, selector, change, true); err != nil {
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}
*/
func (this *Account) Articles(typ string, paging *Paging) (int, []Article, error) {
	var articles []Article
	var query, selector bson.M
	total := 0

	switch typ {
	case "COMMENTS":
		query = bson.M{"author": this.Id, "parent": bson.M{"$ne": nil}}
		//selector = bson.M{"content": 0, "contents": 0}
	case "ARTICLES":
		query = bson.M{"author": this.Id, "parent": nil}
	default:
		query = bson.M{"author": this.Id}
	}

	sortFields := []string{"-pub_time", "-_id"}

	if err := psearch(articleColl, query, selector, sortFields, &total, &articles,
		articlePagingFunc, paging); err != nil {
		e := errors.NewError(errors.DbError, err.Error())
		if err == mgo.ErrNotFound {
			e = errors.NewError(errors.NotFoundError, err.Error())
		}
		return total, nil, e
	}

	for i := 0; i < len(articles); i++ {
		if articles[i].Id.Hex() == paging.First {
			articles = articles[:i]
			break
		} else if articles[i].Id.Hex() == paging.Last {
			articles = articles[i+1:]
			break
		}
	}

	paging.First = ""
	paging.Last = ""
	paging.Count = 0
	if len(articles) > 0 {
		paging.First = articles[0].Id.Hex()
		paging.Last = articles[len(articles)-1].Id.Hex()
		paging.Count = total
	}

	return total, articles, nil
}
示例#17
0
func userRecStatHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, form userRecStatForm) {
	user := &models.Account{}
	stats := &statResp{}
	if find, err := user.FindByUserid(form.Userid); !find {
		e := errors.NewError(errors.NotExistsError, "user not found")
		if err != nil {
			e = errors.NewError(errors.DbError, err.Error())
		}
		writeResponse(request.RequestURI, resp, nil, e)
		return
	}

	stats.RecCount, _ = models.TotalRecords(form.Userid)
	stats.TotalDistance, stats.TotalDuration = redis.RecStats(form.Userid)
	maxDisRec, _ := models.MaxDistanceRecord(form.Userid)
	maxSpeedRec, _ := models.MaxSpeedRecord(form.Userid)

	stats.MaxDistance = &record{}
	if maxDisRec.Sport != nil {
		stats.MaxDistance.Type = maxDisRec.Type
		stats.MaxDistance.Source = maxDisRec.Sport.Source
		stats.MaxDistance.BeginTime = maxDisRec.StartTime.Unix()
		stats.MaxDistance.EndTime = maxDisRec.EndTime.Unix()
		stats.MaxDistance.Duration = maxDisRec.Sport.Duration
		stats.MaxDistance.Distance = maxDisRec.Sport.Distance
	}

	stats.MaxSpeed = &record{}
	if maxSpeedRec.Sport != nil {
		stats.MaxDistance.Type = maxDisRec.Type
		stats.MaxDistance.Source = maxDisRec.Sport.Source
		stats.MaxDistance.BeginTime = maxDisRec.StartTime.Unix()
		stats.MaxDistance.EndTime = maxDisRec.EndTime.Unix()
		stats.MaxSpeed.Duration = maxSpeedRec.Sport.Duration
		stats.MaxSpeed.Distance = maxSpeedRec.Sport.Distance
	}

	stats.Score = user.Props.Score
	stats.Actor = userActor(user.Actor)
	stats.Level = user.Level()
	//stats.Rank = userRank(stats.Level)

	stats.Index = redis.LBDisRank(form.Userid) + 1
	stats.LBCount = redis.LBDisCard()

	writeResponse(request.RequestURI, resp, stats, nil)
}
示例#18
0
文件: msg.go 项目: shevilangle/sports
func (this *Message) Save() error {
	this.Id = bson.NewObjectId()
	if err := save(msgColl, this, true); err != nil {
		return errors.NewError(errors.DbError, err.(*mgo.LastError).Error())
	}

	return nil
}
示例#19
0
func (this *File) Exists() (bool, error) {
	count := 0
	err := search(fileColl, bson.M{"fid": this.Fid}, nil, 0, 0, nil, &count, nil)
	if err != nil {
		return false, errors.NewError(errors.DbError)
	}
	return count > 0, nil
}
示例#20
0
func checkTokenHandler(c martini.Context, p Parameter, redis *models.RedisLogger, r *http.Request, w http.ResponseWriter) {
	uid := redis.OnlineUser(p.TokenId())
	if len(uid) == 0 {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.AccessError))
	}
	fmt.Println("===", p.TokenId(), uid)
	c.Map(&models.Account{Id: uid})
}
示例#21
0
func (this *Article) IsThumbed(userid string) (bool, error) {
	count := 0
	err := search(articleColl, bson.M{"_id": this.Id, "thumbs": userid}, nil, 0, 0, nil, &count, nil)
	if err != nil {
		return false, errors.NewError(errors.DbError, err.Error())
	}
	return count > 0, nil
}
示例#22
0
func (this *Article) RemoveId() error {
	if err := removeId(articleColl, this.Id, true); err != nil {
		if e, ok := err.(*mgo.LastError); ok {
			return errors.NewError(errors.DbError, e.Error())
		}
	}
	return nil
}
示例#23
0
func (group *Group) Save() error {
	group.Id = bson.NewObjectId()
	group.Gid = group.Id.Hex()
	if err := save(groupColl, group, true); err != nil {
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}
示例#24
0
func FindUsersByPhones(phones []string) ([]Account, error) {
	var users []Account

	if err := search(accountColl, bson.M{"phone": bson.M{"$in": phones}}, nil, 0, 0, nil, nil, &users); err != nil {
		return nil, errors.NewError(errors.DbError)
	}

	return users, nil
}
示例#25
0
func (e *Event) Save() error {
	e.Id = bson.NewObjectId()
	if err := save(eventColl, e, true); err != nil {
		log.Println(err)
		return errors.NewError(errors.DbError, err.(*mgo.LastError).Error())
	}

	return nil
}
示例#26
0
func followHandler(request *http.Request, resp http.ResponseWriter,
	client *ApnClient, redis *models.RedisLogger, user *models.Account, p Parameter) {

	form := p.(relationshipForm)

	for _, peer := range form.Userids {
		if redis.Relationship(peer, user.Id) == models.RelBlacklist {
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.DbError, "对方已屏蔽了你!"))
			return
		}
	}

	redis.SetRelationship(user.Id, form.Userids, models.RelFollowing, form.Follow)
	writeResponse(request.RequestURI, resp, map[string]interface{}{"ExpEffect": Awards{}}, nil)

	for _, userid := range form.Userids {
		u := &models.Account{}
		u.FindByUserid(userid)

		event := &models.Event{
			Type: models.EventMsg,
			Time: time.Now().Unix(),
			Data: models.EventData{
				Type: models.EventSub,
				Id:   user.Id + "-" + u.Id,
				From: user.Id,
				To:   u.Id,
				Body: []models.MsgBody{
					{Type: "nikename", Content: user.Nickname},
					{Type: "image", Content: user.Profile},
				},
			},
		}

		if form.Follow {
			/*
				if err := event.Save(); err == nil {
					redis.IncrEventCount(u.Id, event.Data.Type, 1)
				}
			*/
			event.Upsert()

			event.Data.Body = append(event.Data.Body,
				models.MsgBody{Type: "new_count", Content: "1"})
			redis.PubMsg(models.EventMsg, u.Id, event.Bytes())

			// apple push
			if u.Push {
				go sendApn(client, user.Nickname+"关注了你!", u.EventCount("", ""), u.Devs...)
			}
		} else {
			//count := u.DelEvent(models.EventSub, user.Id, user.Id, u.Id)
			//redis.IncrEventCount(u.Id, models.EventSub, -count)
			event.Delete()
		}
	}
}
示例#27
0
func loadUserHandler(c martini.Context, user *models.Account, redis *models.RedisLogger, r *http.Request, w http.ResponseWriter) {
	if find, err := user.FindByUserid(user.Id); !find {
		if err == nil {
			err = errors.NewError(errors.NotExistsError)
		}
		writeResponse(r.RequestURI, w, nil, err)
		return
	}
}
示例#28
0
func (this *Account) SetInfo(setinfo *SetInfo) error {
	change := bson.M{
		"$set": Struct2Map(setinfo),
	}
	if err := updateId(accountColl, this.Id, change, true); err != nil {
		return errors.NewError(errors.DbError)
	}
	return nil
}
示例#29
0
func loginHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, form loginForm) {
	user := &models.Account{}
	var err error
	var reg bool
	token := Uuid() + "-" + strconv.FormatInt(time.Now().AddDate(0, 0, 30).Unix(), 10)

	switch form.Type {
	case "weibo":
		reg, user, err = weiboLogin(form.Userid, form.Password, redis)
	case "weixin":
		writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.UnimplementedError))
		return
	case "usrpass":
		fallthrough
	default:
		var find bool
		if find, err = user.FindByUserPass(strings.ToLower(form.Userid), Md5(form.Password)); !find {
			if err == nil {
				err = errors.NewError(errors.AuthError)
			}
		}
	}

	if err != nil {
		writeResponse(request.RequestURI, resp, nil, err)
		return
	}

	if user.TimeLimit < 0 {
		writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.AuthError, "账户已禁用"))
		return
	}

	redis.SetOnlineUser(token, user.Id)

	data := map[string]interface{}{
		"access_token":    token,
		"userid":          user.Id,
		"register":        reg,
		"last_login_time": user.LastLogin.Unix(),
		"ExpEffect":       Awards{},
	}
	writeResponse(request.RequestURI, resp, data, nil)
}
示例#30
0
func (config *Config) Update() error {
	change := bson.M{
		"$set": config,
	}

	if _, err := upsert(configColl, nil, change, true); err != nil {
		return errors.NewError(errors.DbError, err.Error())
	}
	return nil
}