接上一篇:Meteor项目实战 -- Next 0.0.1html
Get things done , and do Nextgit
Next 0.0.2版的目标是帐户系统,并把任务与用户关联起来。github
首先增长登陆所需路由,修改router.coffee,增长以下代码:shell
Router.route('/login', -> @render("Login") )
增长对应模板,在client/templates/ 下新建login.html,内容以下:segmentfault
<template name="Login"> welcome login </template>
Meteor提供了方便好用的帐户系统。帐户系统的基本功能位于accounts-base
包,但一般都会选择直接引入--登陆服务提供包,例如:ui
accounts-password
accounts-facebook
accounts-github
accounts-google
accounts-meetup
accounts-twitter
accounts-weibo
引入这些包时会自动引入accounts-base
包。this
使用第三方登陆不只能让用户省去繁琐的注册流程,还能大大简化开发。考虑到国情,原本打算使用accounts-weibo
,可是体验了以后发现,微博的接入流程还须要审核一堆材料,因此咱们这里选择引入accounts-github
。google
meteor add accounts-github
观察控制台的输出,咱们发现自动添加的依赖包有:spa
accounts-base added, version 1.2.0 accounts-github added, version 1.0.4 accounts-oauth added, version 1.1.5 github added, version 1.1.3 localstorage added, version 1.0.3 oauth added, version 1.1.4 oauth2 added, version 1.1.3 service-configuration added, version 1.0.4
而后在 mongo shell 中 show collections;
发现同时多了两个集合:localstorage
meteor_accounts_loginServiceConfiguration meteor_oauth_pendingCredentials
从集合的名字推断:大概是用来保存第三方登陆配置和凭证的。
使用第三方登陆服务以前,都须要进行一些配置。最简单的方式就是引入另外一个包 accounts-ui
,它给每个登陆服务提供一个配置向导。
meteor add accounts-ui
而后修改login.html,为
<template name="Login"> {{> loginButtons}} </template>
{{> loginButtons}}
是accounts-ui
包提供的登陆UI。
访问登陆页,会出现一个configure github login的按钮,点击它,会出现一个向导,按照步骤提示进行配置,而后点击save configuration。
这时候按钮变成了sign in with github。
在mongo shell中执行:
db.meteor_accounts_loginServiceConfiguration.find()
能够看到刚才的配置就保存到了这个集合中。
接下来,咱们点击sign in with github。就会跳到github的受权页面,点击赞成,就会跳转回登陆页,按钮变成了sign out,说明已经成功登陆
利用第三方登陆服务成功登陆后,Meteor会自动在users集合中新建对应的用户,到mongo shell中查询,
db.users.find().pretty()
输出结果相似:
到目前为止一切顺利。接下来调整一些细节,当未登陆用户访问时,自动跳转到登陆页。修改router.coffee,增长下面代码:
Router.onBeforeAction(-> if !Meteor.userId() this.redirect('/login') this.next() )
如今咱们有了帐户系统,而后就要把任务和用户关联起来。
首先,新建任务时,同时保存用户的_id
字段,修改home.coffee
Template.home.events 'submit .form-create-task': (e)-> e.preventDefault() $form = $(e.currentTarget) task = name: $form.find('input[name=name]').val() create_time: new Date() important: false urgent: false user_id: Meteor.userId() // 保存用户_id字段 ....后面代码省略
最后,修改发布,只发布当前用户的任务,修改publish.coffee,
Meteor.publish('tasks', -> Task.find({user_id: @userId}) )
Done! ^_^