0

使用 oauth2 使用正确的用户名/密码进行身份验证时,授权它成功进行身份验证。但是当使用身份验证刷新页面时,用户对象会丢失。我正在使用 ember-cli。

以下是所有相关代码:

ember-simple-auth 的初始化程序

//initializers/authentication.js

import OAuth2 from 'simple-auth-oauth2/authenticators/oauth2';
import Session from 'simple-auth/session';
import UserModel from 'client/models/user';

export default {
  name: 'authentication',
  before: 'simple-auth',

  initialize: function(container) {
    window.ENV = window.ENV || {};
    window.ENV['simple-auth'] = {
      authenticationRoute: 'login',
      routeAfterAuthentication: 'me.index',
      authorizer: 'simple-auth-authorizer:oauth2-bearer',
      crossOriginWhitelist: [ClientENV.apiEndpoint]
    };

    window.ENV['simple-auth-oauth2'] = {
      serverTokenEndpoint: ClientENV.apiEndpoint + '/auth',
      refreshAccessTokens: true,
    };

    // This doesn't work. This gets called but never gets saved in the session object.
    Session.reopen({
      user: function() {
        return UserModel.currentUser().then(function(user) {
          return user;
        });
      }.property()
    });

    OAuth2.reopen({
      makeRequest: function (url, data) {
        data.client_id = 'web-client';
        return this._super(url, data);
      }
    });
  }
};

申请途径:

//routes/application.js

import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
import UserModel from 'client/models/user';
import Configuration from 'simple-auth/configuration';

export default Ember.Route.extend(ApplicationRouteMixin, {
  actions: {
    sessionAuthenticationSucceeded: function() {
      var self = this;
      UserModel.currentUser().then(function(user) {
        self.get('session').set('user', user);
        var attemptedTransition = self.get('session').get('attemptedTransition');
        if (attemptedTransition) {
          attemptedTransition.retry();
          self.get('session').set('attemptedTransition', null);
        } else {
          self.transitionTo(Configuration.routeAfterAuthentication);
        }
      })
    }
  }
});

应用程序的用户模型

//models/user.js
import Ember from 'ember';
import { request } from 'ic-ajax';

var UserModel = Ember.Object.extend({
  username: null,
  email: null,
  firstname: null,
  lastname: null,
  role: null,

  fullname: function() {
    return this.get('firstname') + ' ' + this.get('lastname');
  }.property('firstname', 'lastname')

});

UserModel.reopenClass({
  currentUser: function() {
    return request({
      url: ClientENV.apiEndpoint + '/user/me',
      type: 'GET'
    });
  }
});

export default UserModel;

整个代码也在这里:Gist for the code

4

0 回答 0