在Ember.js/Rails/Devise应用程序中处理用户注册

5

我正在尝试在Rails 4上编写一个纯Ember.js应用程序,但我对用户管理如何处理感到困惑。 我最初的想法是使用服务器端呈现的模板(ERB)通过Devise进行用户注册和登录,然后应用程序的其余部分将使用Ember框架。

问题在于Ember希望接管<body>标签并控制整个视口。这样一来,我就无法选择哪些方面的应用程序应该使用服务器呈现的Er b模板,哪些方面应该在Ember逻辑中运行。

我看到很多关于如何处理已经登录的用户的示例,ember-auth 看起来很有趣,可以促进认证感知控制器,但我没有看到任何关于允许完整用户注册体验在Ember应用程序中发生的教程或建议。

我有什么遗漏的吗?从技术角度来看,我是否错过了正确的代码,或者从架构角度来看,我是否不应该以这种方式处理?

这是使用ember-rails(0.12.0 w /1.0.0.rc3.3 ember-source),Rails 4.0.0.rc1和Devise(rails4分支)。

3个回答

6

ember-auth 的开发者在此。

实际上,您不需要为用户注册提供任何特殊处理。将用户注册视为另一个模型一样对待即可,也就是说创建一个user模型不需要身份验证。(但编辑或删除它应该需要身份验证。)

您的实现可能如下所示:

App.User = DS.Model.extend
  email: DS.attr 'string'
  password: DS.attr 'string'

App.UsersNewRoute = Em.Route.extend
  model: ->
    App.User.createRecord()

App.UsersNewController = Em.ObjectController.extend 
  create: ->
    @store.commit()

为了简洁起见,错误检查、模板代码等被省略。


1
@heartsentwined 如果你能回答 @flynfish 的问题,我会很感激!我也有同样的问题。有没有一种方法可以在不特别调用API端点的情况下向ember-auth提供令牌? - Brandon
有效的使用案例。我会在有时间的时候制作一个适当的公共API。目前为止:
  1. ember-auth一个JSON,与你从POST /sign-in调用中返回的JSON相同:App.Auth.get('_response').canonicalize(json);
  2. 发送一个signInSuccess事件:App.Auth.trigger('signInSuccess');
- heartsentwined
1
@heartsentwined @Brandon 那个方法奏效了,我将它设置在用户模型的 didCreate 方法中:didCreate: function(model) { App.Auth.get('_response').canonicalize(model); App.Auth.trigger('signInSuccess'); } - flynfish
针对谷歌用户的更新:在最新版本(9.x)中,您可以在路由、控制器和视图中调用 this.get('auth').createSession()this.get('auth').destroySession) - heartsentwined
我认为出于安全考虑,密码不应该作为用户模型的一部分。并且在将密码发送到服务器后,也应该从客户端中删除它。 - Benedikt
显示剩余3条评论

1

这里提供参考,基于@heartsentwined的答案,因为在评论中粘贴不太好用。有关更多信息,请参阅评论。由于我的api返回用户json,所以我只需传递它期望的格式。

didCreate: function() {
  var user = App.Auth.get('_response').response.user;
  var auth = {auth_token: user.auth_token, id: user.id};
  App.Auth.get('_response').canonicalize(auth);
  App.Auth.trigger('signInSuccess');
}

更新: 我转换到了ember-model,现在在与我调用model.save()相同的位置执行此操作(即SignupController的submit动作)。

var model = this.get('model'); 
model.on('didCreateRecord', function() { 
  var user = this.data;
  var auth = {auth_token: user.auth_token, user_id: user.id, remember_token: user.remember_token};
  App.Auth.get('_response').canonicalize(auth);
  App.Auth.trigger('signInSuccess');
}); 

model.save();

1

以上的解决方案对我来说几乎有用,但还不够完美。这是真正有效的方法:

didCreate: function() {
  var user = App.Auth.get('_response').response.user;
  App.Auth.signIn({
    data: {
      'email':    user.email,
      'password': this.get('password'),
      'remember': true
    }
  });
}

文档中明确使用了 App.Auth.signIn:http://ember-auth.herokuapp.com/docs


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接