login.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter web
  5. name:login.py 登录相关接口
  6. author:rabin
  7. """
  8. from __load__ import *
  9. import json
  10. import urllib
  11. import urllib2
  12. class login_path(Load):
  13. """
  14. @api {get} /login 登录绑定
  15. @apiVersion 1.0.0
  16. @apiName Login
  17. @apiGroup Common
  18. @apiParam {String} code 微信小程序的code
  19. @apiParam {String} mobile 手机号
  20. @apiParam {String} password 密码
  21. @apiSuccess {String} uid 用户id(加密之后的)
  22. @apiErrorExample 操作成功
  23. {"status": 1, "msg": "yes", "code": 0, "data": {"uid": "111"}]}}
  24. @apiErrorExample 操作失败
  25. {"status": 2, "msg": "\u64cd\u4f5c\u5931\u8d25", "code": 0, "data": {}}
  26. """
  27. @Web.setting
  28. def get(self):
  29. mobile = self.input('mobile')
  30. password = self.input('password')
  31. if mobile and password:
  32. user = self.service('common').one('farm_user', mobile=mobile)
  33. if user:
  34. temp = user['password'].split('_')
  35. if Demeter.md5(password, temp[1]) == user['password']:
  36. state = self.bind(user['id'])
  37. if not state:
  38. self.out('手机号或密码错误,登录失败')
  39. else:
  40. #self.set_secure_cookie('user', str(user['id']))
  41. #self.redirect('/')
  42. self.out('yes', {'uid':user['id']})
  43. return
  44. else:
  45. self.out('手机号或密码错误,登录失败')
  46. return
  47. @Web.setting
  48. def bind(self, uid):
  49. code = self.input('code')
  50. if not code:
  51. self.out('no')
  52. return
  53. url = Demeter.config['weixinApp']['login']
  54. url = url + '?appid=' + Demeter.config['weixinApp']['appid']
  55. url = url + '&secret=' + Demeter.config['weixinApp']['secret']
  56. url = url + '&js_code=' + code
  57. url = url + '&grant_type=authorization_code'
  58. req = urllib2.Request(url)
  59. response = urllib2.urlopen(req)
  60. data = json.loads(response.read())
  61. #data = Demeter.curl(url)
  62. #data = json.loads(data.body)
  63. print data
  64. if 'errcode' in data:
  65. return False
  66. update = {}
  67. update['openid'] = data['openid']
  68. update['session_key'] = data['session_key']
  69. self.service('common').update('farm_user', uid, update)
  70. return True