Login.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\service\DingtalkService;
  4. use app\common\model\User;
  5. use Firebase\JWT\JWT;
  6. use hg\apidoc\annotation as Apidoc;
  7. /**
  8. * @Apidoc\Title("登录")
  9. * @Apidoc\Group("api")
  10. * @Apidoc\Sort("1")
  11. */
  12. class Login extends Base
  13. {
  14. /**
  15. * 登录
  16. *
  17. * @Apidoc\Method("POST")
  18. * @Apidoc\Param("code", type="string",require=true, desc="免登授权码")
  19. * @Apidoc\Returned("data", type="string", desc="用户token")
  20. */
  21. public function login(){
  22. $code = input('code');
  23. if(!$code){
  24. $this->error('授权码错误');
  25. }
  26. $resp = DingtalkService::get_user_info($code);
  27. if($resp->errcode != 0){
  28. $this->error($resp->errcode.' '.$resp->errmsg);
  29. }
  30. $user = User::where('userid',$resp->result->userid)->value('id');
  31. if(!$user){
  32. $this->error('不是内部人员');
  33. }
  34. $token = $this->create_jwt($user);
  35. $this->success('登录成功',$token);
  36. }
  37. /**
  38. * 获取token
  39. *
  40. * @Apidoc\Method("POST")
  41. * @Apidoc\Query("uid", type="string",require=true, desc="用户ID")
  42. * @Apidoc\Returned("data", type="string", desc="用户token")
  43. */
  44. public function get_token(){
  45. $uid = input('uid');
  46. $token = $this->create_jwt($uid);
  47. $this->success('获取成功',$token);
  48. }
  49. //token加密
  50. public function create_jwt($uid)
  51. {
  52. $key = md5(config('app.jwt')); //jwt的签发密钥,验证token的时候需要用到
  53. $time = time(); //签发时间
  54. $expire = $time + config('app.jwt_time'); //过期时间
  55. $token = array(
  56. "uid" => $uid,
  57. "iss" => "https://zain.com",//签发组织
  58. "aud" => "https://zain.com", //签发作者
  59. "iat" => $time,
  60. "nbf" => $time,
  61. "exp" => $expire
  62. );
  63. $jwt = JWT::encode($token, $key);
  64. return $jwt;
  65. }
  66. }