®
The World’s Top Talent, On Demand ®

Copyright 2010 - 2024 Toptal, LLC

\n\n\n \n\n\n

Below is the code that we need in main.Js配置路由:

\n\n
Var app = angular.模块(“DemoApp”,[' ui.路由器']);\n\napp.配置(function (stateProvider美元, urlRouterProvider美元) {\n  stateProvider美元\n    .状态(“回家”,{\n      url:“/ home”,\n      templateUrl: 'partials/home.tpl.html的\n    })\n    .状态(“秘密”,{\n      url:“/秘密”,\n      templateUrl: 'partials/secret.tpl.html的,\n    })\n    .状态(“登录”,{\n      url: /登录,\n      templateUrl: 'partials/login.tpl.html的\n    });\n  urlRouterProvider美元.否则(/ home);\n\n});\n
\n\n

At this point if you run the server python app.py, you should have this basic interface at http://localhost:5000

\n\n

\"基本登录界面\"

\n\n

链接主页, 登录, 和Secret应该在这一点上工作,并显示相应模板的内容.

\n\n

恭喜你,你刚刚搭建好了骨架! \nIf you encounter any error, please check out the 代码在GitHub

\n\n

Step #2: 登录 and Register

\n\n

在这一步的最后,你将有一个web应用程序,你可以使用电子邮件和密码注册/登录.

\n\n

The first step is to 配置ure the backend. 我们需要一个User模型和一种为给定用户生成JWT令牌的方法. 下面显示的User模型实际上是简化的,它甚至不执行任何基本的检查,比如if字段 电子邮件 包含“@”或if字段 密码 contains at least 6 characters, etc.

\n\n
类用户(db.模型):\n    Id = db.列(db.Integer, primary_key=True)\n    Email = db.列(db.String(100), nullable=False)\n    密码= db.列(db.字符串(100))\n\n    def令牌(自我):\n        有效载荷= {\n            “子”:自我.id,\n            “iat”:datetime.utcnow (),\n            “实验”:datetime.utcnow() + timedelta(days=14)\n        }\n        令牌= JWT.编码(负载应用.配置[' TOKEN_SECRET '])\n        返回令牌.解码(“unicode_escape”)\n
\n\n

我们使用python中的jwt模块在jwt中生成有效负载部分. iat和exp部分对应于令牌创建和过期的时间戳. In this code, the token will be expired in 2 weeks.

\n\n

在创建模型User之后,我们可以添加“login”和“register”端点. 两者的代码非常相似,所以这里我只展示“寄存器”部分. 请注意,默认情况下,Satellizer将调用端点 /身份验证/登录 and /认证/注册 for the “login” and “register” respectively.

\n\n
@app.route('/认证/注册', methods=['POST'])\ndef注册():\n    数据=请求.json\n\n    电子邮件 = data[\"电子邮件\"]\n    密码 = data[\"密码\"]\n\n    user =用户(电子邮件=电子邮件, 密码=密码)\n    db.会话.添加(用户)\n    db.会话.commit ()\n\n    返回jsonify(令牌=用户.令牌())\n
\n\n

Let’s check the endpoint using curl first:

\n\n
curl localhost:5000/认证/注册 -H \"Content-Type: application/json\" -X POST -d '{\"电子邮件\":\"test@abcd.com\",\"密码\":\"xyz\"}'\n
\n\n

The result should look like this:

\n\n
{\n  \"token\": \"very long string….\"\n}\n
\n\n

现在后端部分已经准备好了,让我们来攻击前端! 首先,我们需要安装satellizer,并将它作为一个依赖项添加到main中.js:

\n\n
bower install satellizer --save\n
\n\n

Add satellizer as dependency:

\n\n
Var app = angular.模块(“DemoApp”,[' ui.路由器”、“satellizer ']);\n
\n\n

与目前为止的所有设置相比,在satellizer中登录和注册实际上非常简单:

\n\n
美元的范围.signUp = function () {\n    美元的身份验证\n      .注册({电子邮件:美元范围.电子邮件,密码:美元的范围.密码})\n      .then(function (response) {\n        // set the token received from server\n        美元的身份验证.setToken(响应);\n        //进入秘密页面\n        美元的国家.(“秘密”);\n      })\n      .catch(function (response) {\n        控制台.log(\"error response\", response);\n      })\n  };\n
\n\n

如果您在设置代码时遇到任何困难,可以查看 代码在GitHub.

\n\n

步骤3:但秘密视图并不是真正的秘密,因为任何人都可以看到它!

\n\n

是的,这是正确的! 到目前为止,任何人都可以不登录就进入秘密页面.

\n\n

是时候在AngularJS中添加一些拦截器了,以确保如果有人进入了秘密页面,并且这个用户没有登录, they will be redirected to the login page.

\n\n

首先,我们应该添加一个required登录标志来区分秘密页面和其他页面.

\n\n
    .状态(“秘密”,{\n      url:“/秘密”,\n      templateUrl: 'partials/secret.tpl.html的,\n      控制器:“SecretCtrl”,\n      data: {required登录: true}\n    })\n
\n\n

" data "部分将在美元的国家ChangeStart事件中使用,该事件在每次路由更改时触发:

\n\n
app.run(function (rootScope美元, 美元的国家, 美元的身份验证) {\n  rootScope美元.美元(“stateChangeStart美元”,\n    function (事件, toState) {\n      var required登录 = false;\n      // check if this state need login\n      如果(toState.data && toState.data.required登录)\n        required登录 = true;\n      \n      //如果是,如果这个用户没有登录,重定向到登录页面\n      如果(required登录 && !美元的身份验证.isAuthenticated ()) {\n        事件.pr事件Default ();\n        美元的国家.(“登录”);\n      }\n    });\n});\n
\n\n

现在,用户不登录就不能直接进入秘密页面. 万岁!

\n\n

As usual, the code of this step can be found here.

\n\n

Step #4: It’s Time to Get Something Really Secret!

\n\n

此时此刻,秘密页上没有什么真正的秘密. Let’s put something personal there.

\n\n

此步骤首先在后端创建一个端点,该端点只能由经过身份验证的用户访问, such as having a valid token. 端点 /用户 返回 user_id and 电子邮件 of the user corresponding to the token.

\n\n
@app.路线(“/用户”)\ndef user_info ():\n    # the token is put in the 授权 header\n    如果不要求.头.得到(“授权”):\n        返回jsonify(error='授权 header missing')\n    \n    #这个头看起来像这样:"授权:承载{令牌}"\n    令牌=请求.头.get(“授权”).split () [1]\n    try:\n        有效载荷= JWT.解码(令牌,应用.配置[' TOKEN_SECRET '])\n    除了DecodeError:\n        return jsonify(error='Invalid token'), 401\n    除了ExpiredSignature:\n        return jsonify(error='Expired token'), 401\n    其他:\n        User_id = payload['sub']\n        user =用户.查询.filter_by (id = user_id).第()\n        如果user为None:\n            return jsonify(error='Should not happen ...'), 500\n        返回jsonify(用户id =.=用户id、电子邮件.电子邮件),200\n    return jsonify(error=\"never reach here...\"), 500\n
\n\n

Again, we make use of the module jwt 解码包含在“授权”头中的JWT令牌,并处理令牌过期或无效的情况.

\n\n

Let’s test this endpoint using curl. First, we need to get a valid token:

\n\n
curl localhost:5000/认证/注册 -H \"Content-Type: application/json\" -X POST -d '{\"电子邮件\":\"test@abcd.com\",\"密码\":\"xyz\"}'\n
\n\n

然后用这个记号:

\n\n
curl localhost:5000/用户 -H \"授权: Bearer {put the token here}\"\n
\n\n

结果如下:

\n\n
{\n  \"电子邮件\": \"test@abcd.com\",\n  \"id\": 1\n}\n
\n\n

现在我们需要在Secret Controller中包含这个端点. 这很简单,因为我们只需要使用常规的http美元模块调用端点. 令牌由Satellizer自动插入报头, 因此,我们不需要为保存令牌并将其放入正确的头部的所有细节而烦恼.

\n\n
  getUserInfo ();\n\n  getUserInfo() {\n    http美元.get(/用户)\n      .then(function (response) {\n        美元的范围.用户=响应.数据;\n      })\n      .catch(function (response) {\n        控制台.log(\"getUserInfo error\", response);\n      })\n  }\n
\n\n

终于,我们的秘密页面里有了真正私人的东西!

\n\n

\"The

\n\n

The code of this step is on GitHub.

\n\n

Step #5: 脸谱网 登录 with Satellizer

\n\n

A nice thing about Satellizer, as mentioned at the beginning, is it makes integrating social login a lot easier. 在这一步的最后,用户可以使用他们的脸谱网帐户登录!

\n\n

\"脸谱网

\n\n

首先要做的是在脸谱网开发者页面上创建一个应用程序 application_id 还有一个密码. 请跟 开发人员.脸谱网.com/docs/apps/register 创建一个脸谱网开发者账户(如果你还没有),并创建一个网站应用程序. 之后,您将获得应用程序ID和应用程序秘密,如下面的截图所示.

\n\n

\"Getting

\n\n

Once the user chooses to connect with 脸谱网, Satellizer将向终端发送授权码 /认证/ 脸谱网. 有了这个授权码,后端就可以从脸谱网检索访问令牌 / oauth 端点,允许调用脸谱网 Graph API来获取用户信息,如位置, user_friends, 用户的电子邮件, etc.

\n\n

我们还需要跟踪用户帐户是通过脸谱网创建的还是通过常规注册创建的. 为此,我们添加 脸谱网_id 到我们的用户模型.

\n\n
脸谱网_Id = db.列(db.字符串(100)) \n
\n\n

脸谱网的秘密是通过我们添加的环境变量FACEBOOK_SECRET来配置的 app.配置.

\n\n
app.配置['FACEBOOK_SECRET'] = os.环境.get(“FACEBOOK_SECRET”)\n
\n\n

所以要启动 app.py, you should set this env variable:

\n\n
FACEBOOK_SECRET={your secret} python app.py\n
\n\n

Here is the method which handles 脸谱网 logins. By default Satellizer will call the endpoint /认证/ 脸谱网.

\n\n
@app.route('/认证/ 脸谱网', methods=['POST'])\ndef auth_脸谱网 ():\n    access_token_url = 'http://graph.脸谱网.com/v2.3 / oauth / access_token '\n    graph_api_url = 'http://graph.脸谱网.com/v2.5/me?=字段id、电子邮件的\n\n    参数= {\n        “client_id”:请求.json(“clientId”),\n        “redirect_uri”:请求.json(“redirectUri”),\n        “client_secret”:应用程序.配置['FACEBOOK_SECRET'],\n        “代码”:请求.json(“代码”)\n    }\n\n    # Exchange authorization code for access token.\n    R =请求.get(access_token_url, params=params)\n    #使用json.加载而不是urlparse.parse_qsl\n    Access_token = json.负载(右.文本)\n\n    #第二步. Retrieve information about the current user.\n    R =请求.get(graph_api_url, params=access_token)\n    Profile = json.负载(右.文本)\n\n    #步骤3. Create a new account or return an existing one.\n    user =用户.查询.filter_by(脸谱网_id=profile['id']).第()\n    如果用户:\n        返回jsonify(令牌=用户.令牌())\n\n    u = User(脸谱网_id=profile['id'], 电子邮件=profile['电子邮件'])\n    db.会话.添加(u)\n    db.会话.commit ()\n    返回jsonify(令牌= u.令牌())\n
\n\n

为了向脸谱网服务器发送请求,我们使用了方便的请求模块.\nNow the difficult part on the back-end is done. 在前端,添加脸谱网登录非常简单. First, we need to tell Satellizer our 脸谱网_id 将此代码添加到 app.配置 功能:

\n\n
authProvider美元.脸谱网 ({\n    clientId: {your 脸谱网 app id},\n    //默认情况下,重定向URI为http://localhost:5000\n    redirectUri: 'http://localhost:5000/static/index.html的\n  });\n
\n\n

To login using 脸谱网, we can just call:

\n\n
美元的身份验证.验证(“脸谱网”)\n
\n\n

As usual, you can check the 代码在GitHub

\n\n

此时,web应用程序在功能方面是完整的. 用户可以使用普通的电子邮件和密码登录/注册,也可以使用脸谱网. Once logged in, the user can see his secret page.

\n\n

制作漂亮的界面

\n\n

The interface is not very pretty at this point, 因此,让我们为布局和角烤面包机模块添加一点Bootstrap,以便更好地处理错误消息, 例如登录失败.

\n\n

The code for this beautifying part can be found here.

\n\n

结论

\n\n

本文展示了如何一步一步地将Satellizer集成到一个(简单的)AngularJS web应用中. 使用Satellizer,我们可以很容易地添加其他社交登录,如推特, Linkedin等. 前端的代码与本文中的代码完全相同. 然而, 后端不同,因为社交网络sdk有不同的端点和不同的协议. You can take a look at http://github.com/sahat/satellizer/blob/master/examples/server/python/app.它包含脸谱网, Github, Google, Linkedin, 推特和Bitbucket都的示例. 如果有疑问,您应该查看有关的文档 http://github.com/sahat/satellizer.

\n","as":"div","isContentFit":true,"sharingWidget":{"url":"http://we6a.flcoastline.com/angular-js/Facebook-login-angularjs-app-satellizer","title":"身份验证 in AngularJS Apps with Satellizer","text":null,"providers":["linkedin","推特","脸谱网"],"gaCategory":null,"domain":{"name":"开发人员","title":"工程","vertical":{"name":"开发人员","title":"开发人员","publicUrl":"http://we6a.flcoastline.com/Developers"},"publicUrl":"http://we6a.flcoastline.com/Developers/blog"},"hashtags":"AngularJS,Social登录,Satellizer"}}