2014-12-10 18:26:38 +08:00
|
|
|
#coding=utf-8
|
|
|
|
|
2014-11-27 19:43:04 +08:00
|
|
|
module Mobile
|
2014-12-09 16:36:43 +08:00
|
|
|
|
|
|
|
module Entities
|
|
|
|
class Auth < Grape::Entity
|
|
|
|
expose :token
|
|
|
|
expose :user, using: User
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2014-12-09 15:16:47 +08:00
|
|
|
module Apis
|
|
|
|
class Auth < Grape::API
|
|
|
|
resource :auth do
|
2014-12-10 15:11:10 +08:00
|
|
|
desc "用户登录"
|
2014-12-09 15:16:47 +08:00
|
|
|
params do
|
|
|
|
requires :login, type: String, desc: 'Username or email'
|
|
|
|
requires :password, type: String, desc: 'Password'
|
|
|
|
end
|
2014-12-10 15:11:10 +08:00
|
|
|
post do
|
2014-12-09 15:16:47 +08:00
|
|
|
user,last_logon = ::User.try_to_login(params[:login], params[:password])
|
|
|
|
if user
|
|
|
|
::ApiKey.delete_all(user_id: user.id)
|
|
|
|
key = ::ApiKey.create!(user_id: user.id)
|
2014-12-09 16:57:08 +08:00
|
|
|
api_user = ::UsersService.new.show_user({id:user.id})
|
|
|
|
present :data, {token: key.access_token, user: api_user}, using: Entities::Auth
|
2014-12-09 16:36:43 +08:00
|
|
|
present :status, 0
|
2014-12-09 15:16:47 +08:00
|
|
|
else
|
2014-12-10 17:29:39 +08:00
|
|
|
raise 'Unauthorized.'
|
2014-12-09 15:16:47 +08:00
|
|
|
end
|
2014-11-27 19:43:04 +08:00
|
|
|
end
|
2014-12-10 15:11:10 +08:00
|
|
|
|
|
|
|
desc "用户登出"
|
|
|
|
params do
|
2014-12-10 16:23:56 +08:00
|
|
|
requires :token, type: String
|
2014-12-10 15:11:10 +08:00
|
|
|
end
|
|
|
|
delete do
|
|
|
|
authenticate!
|
|
|
|
::ApiKey.delete_all(user_id: current_user.id)
|
|
|
|
{status: 0}
|
|
|
|
end
|
|
|
|
|
2014-11-27 19:43:04 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|