require 'rails_helper' require 'mks/auth/token_auth' module Mks module Auth RSpec.describe UsersController, type: :controller do routes { Mks::Auth::Engine.routes } describe 'GET #roles' do it 'gets roles of a user' do u = create(:user) token = Mks::Auth::TokenAuth.issue(name: u.full_name, email: u.email, id: u.id) request.headers['Authorization'] = "Bearer #{token}" roles = [create(:user_role), create(:user_role)] u.roles << roles get :roles, params: { id: u.id } result = JSON(response.body) expect(result['data'].count).to eq 2 end end describe 'GET #user_roles' do it 'fetches roles' do app_module = create(:application_module, code: 'DUMMY') u = create(:user, application_modules: [app_module]) token = Mks::Auth::TokenAuth.issue(name: u.full_name, email: u.email, id: u.id) request.headers['Authorization'] = "Bearer #{token}" r1 = create(:user_role, application_module: app_module) r2 = create(:user_role, application_module: app_module) u.roles << r1 get :user_roles, params: { id: u.id } result = JSON(response.body) expect(result.count).to eq 2 expect(result.select { |r| r['id'] == r1.id }[0]['selected']).to be_truthy expect(result.select { |r| r['id'] == r2.id }[0]['selected']).to be_falsey end end describe 'POST #save_selected_roles' do it 'saves selected user roles' do app_module = create(:application_module, code: 'DUMMY') u = create(:user, application_modules: [app_module]) token = Mks::Auth::TokenAuth.issue(name: u.full_name, email: u.email, id: u.id) request.headers['Authorization'] = "Bearer #{token}" r1 = create(:user_role, application_module: app_module) r2 = create(:user_role, application_module: app_module) roles = [ { id: r1.id, selected: true }, { id: r2.id, selected: true } ] post :save_selected_roles, params: { id: u.id, roles: roles } u.reload expect(u.roles.count).to eq 2 end end describe 'POST #login' do it 'returns a jwt token for correct credentials' do m = create(:application_module) ur = create(:user_role, application_module: m) u = create(:user, password: '123456', password_confirmation: '123456', roles: [ur], application_modules: [m]) auth = { email: u.email, password: '123456', app_module: m.code } token = Mks::Auth::TokenAuth.issue(u.to_token_payload) post :login, params: { auth: auth } result = JSON(response.body) expect(result['jwt']).to eq token end it 'returns a 401 status for failed logins' do u = create(:user) auth = { email: u.email, password: '123456' } post :login, params: { auth: auth } expect(response.status).to eq 400 end end end end end