注册和登录 API

This commit is contained in:
jysperm
2014-02-24 01:53:32 +08:00
parent 67d82c2fcb
commit 428d468666
3 changed files with 73 additions and 3 deletions

View File

@@ -20,9 +20,9 @@ Exception:
* username_exist
* email_exist
* invalid_username
* invalid_email
* invalid_passwd
* invalid_username `/^[0-9a-z_]+$/`
* invalid_email `/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/`
* invalid_passwd `/^.+$/`
### POST /user/login/

View File

@@ -65,6 +65,24 @@ module.exports = class User extends Model
, ->
callback() if callback
# @return bool
matchPasswd: (passwd) ->
return auth.hashPassword(passwd, @data.passwd_salt) == @data.passwd
@byUsername: (username, callback) ->
@findOne
username: username
, (err, result) ->
throw err if err
callback result
@byEmail: (email, callback) ->
@findOne
email: email
, (err, result) ->
throw err if err
callback result
# 添加分组的功能
# @group 可以是数组,也可以是字符串,但是必须在['admin','user','trial']中
# @callback 第一个参数是err,第二个参数是添加分组后的model

View File

@@ -1,3 +1,5 @@
User = require '../model/User'
module.exports =
get:
signup: (req, res) ->
@@ -8,6 +10,56 @@ module.exports =
post:
signup: (req, res) ->
data = req.body
if not /^[0-9a-z_]+$/.test data.username
return res.json 400, error: 'invalid_username'
if not /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test data.email
return res.json 400, error: 'invalid_email'
if not data.passwd or not /^.+$/.test data.passwd
return res.json 400, error: 'invalid_passwd'
User.byUsername data.username, (account) ->
if account
return res.json 400, error: 'username_exist'
User.byEmail data.email, (account) ->
if account
return res.json 400, error: 'email_exist'
User.register data.username, data.email, data.password, (account) ->
account.createToken {}, (token)->
res.cookie 'token', token,
expires: new Date(Date.now() + 30 * 24 * 3600 * 1000)
return res.json
id: account.data._id
login: (req, res) ->
data = req.body
# @param callback(account)
getAccount = (callback) ->
User.byUsername data.username, (account) ->
if account
return callback account
User.byEmail data.email, (account) ->
return callback account
getAccount (account) ->
if not account
return res.json 400, error: 'auth_failed'
if not account.matchPasswd data.password
return res.json 400, error: 'auth_failed'
account.createToken {}, (token)->
res.cookie 'token', token,
expires: new Date(Date.now() + 30 * 24 * 3600 * 1000)
return res.json
id: account.data._id
token: token