RIFT-16172: Project switch does not affect polling and socket pages.
[osm/UI.git] / skyquake / framework / core / modules / api / sessions.js
1 /*
2 *
3 * Copyright 2016 RIFT.IO Inc
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 /**
20 * sessions api module. Provides API functions for sessions
21 * @module framework/core/modules/api/sessions
22 * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
23 */
24
25 var Promise = require('bluebird');
26 var constants = require('../../api_utils/constants');
27 var utils = require('../../api_utils/utils');
28 var request = utils.request;
29 var rp = require('request-promise');
30 var sessionsAPI = {};
31 var _ = require('lodash');
32 var base64 = require('base-64');
33 var APIVersion = '/v2';
34 var configurationAPI = require('./configuration');
35
36 function logAndReject(mesg, reject, errCode) {
37 res.errorMessage = {
38 error: mesg
39 }
40 res.statusCode = errCode || constants.HTTP_RESPONSE_CODES.ERROR.BAD_REQUEST;
41 console.log(mesg);
42 reject(res);
43 }
44
45 function logAndRedirectToLogin(mesg, res, req) {
46 var api_server = req.query['api_server'] || (req.protocol + '://' + configurationAPI.globalConfiguration.get().api_server);
47 var upload_server = req.protocol + '://' + (configurationAPI.globalConfiguration.get().upload_server || req.hostname);
48 console.log(mesg);
49 res.redirect('login.html?api_server=' + api_server + '&upload_server=' + upload_server);
50 res.end();
51 }
52
53 sessionsAPI.create = function(req, res) {
54 var api_server = req.query["api_server"];
55 var uri = utils.confdPort(api_server);
56 var login_url = uri + APIVersion + '/api/login';
57 var project_url = uri + APIVersion + '/api/operational/project';
58 var authorization_header_string = 'Basic ' + base64.encode(req.body['username'] + ':' + req.body['password']);
59 return new Promise(function(resolve, reject) {
60 Promise.all([
61 rp({
62 url: login_url,
63 method: 'POST',
64 headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
65 'Authorization': authorization_header_string
66 }),
67 forever: constants.FOREVER_ON,
68 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
69 resolveWithFullResponse: true
70 }),
71 rp({
72 url: project_url,
73 method: 'GET',
74 headers: _.extend({}, constants.HTTP_HEADERS.accept.collection, {
75 'Authorization': authorization_header_string
76 }),
77 forever: constants.FOREVER_ON,
78 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
79 resolveWithFullResponse: true
80 })
81
82 ]).then(function(results) {
83 // results[0].statusCode => 200/201
84 // results[1].body.collection['rw-project:project'] => List of projects OR 204 with no content
85 if (results[0].statusCode != constants.HTTP_RESPONSE_CODES.SUCCESS.OK) {
86 var errorMsg = 'Invalid credentials provided!';
87 logAndRedirectToLogin(errorMsg, res, req);
88 return;
89 }
90
91 var username = req.body['username'];
92 var project_list_for_user = [];
93
94 if (results[1].statusCode == constants.HTTP_RESPONSE_CODES.SUCCESS.NO_CONTENT) {
95 console.log('No projects added or user ', username ,' not privileged to view projects.');
96 } else {
97 // go through projects and get list of projects that this user belongs to.
98 // pick first one as default project?
99
100 var projects = JSON.parse(results[1].body).collection['rw-project:project'];
101 projects && projects.map(function(project) {
102 project['project-config'] &&
103 project['project-config']['user'] &&
104 project['project-config']['user'].map(function(user) {
105 if (user['user-name'] == username) {
106 project_list_for_user.push(project.name);
107 }
108 });
109 });
110
111 req.session.projectId = (project_list_for_user.length > 0) && project_list_for_user.sort() && project_list_for_user[0];
112 }
113
114 req.session.authorization = authorization_header_string;
115 req.session.loggedIn = true;
116 req.session.userdata = {
117 username: username,
118 // project: req.session.projectId
119 };
120 var successMsg = 'User => ' + username + ' successfully logged in.';
121 successMsg += req.session.projectId ? 'Project => ' + req.session.projectId + ' set as default.' : '';
122
123 console.log(successMsg);
124
125 var response = {
126 statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.CREATED,
127 data: JSON.stringify({
128 status: successMsg
129 })
130 };
131
132 req.session.save(function(err) {
133 if (err) {
134 console.log('Error saving session to store', err);
135 }
136 })
137
138 resolve(response);
139
140 }).catch(function(error) {
141 // Something went wrong - Redirect to /login
142 var errorMsg = 'Error logging in or getting list of projects. Error: ' + error;
143 console.log(errorMsg);
144 logAndRedirectToLogin(errorMsg, res, req);
145 });
146 })
147 };
148
149 sessionsAPI.addProjectToSession = function(req, res) {
150 return new Promise(function(resolve, reject) {
151 if (req.session && req.session.loggedIn == true) {
152 req.session.projectId = req.params.projectId;
153 req.session.save(function(err) {
154 if (err) {
155 console.log('Error saving session to store', err);
156 }
157 var successMsg = 'Added project ' + req.session.projectId + ' to session ' + req.sessionID;
158 console.log(successMsg);
159
160 return resolve ({
161 statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK,
162 data: JSON.stringify({
163 status: successMsg
164 })
165 });
166
167 var errorMsg = 'Session does not exist or not logged in';
168 logAndReject(errorMsg, reject, constants.HTTP_RESPONSE_CODES.ERROR.NOT_FOUND);
169 });
170 }
171 });
172 }
173
174 sessionsAPI.delete = function(req, res) {
175 var api_server = req.query["api_server"];
176 var uri = utils.confdPort(api_server);
177 var url = uri + '/api/logout';
178 return new Promise(function(resolve, reject) {
179 Promise.all([
180 rp({
181 url: url,
182 method: 'POST',
183 headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
184 'Authorization': req.session.authorization
185 }),
186 forever: constants.FOREVER_ON,
187 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
188 resolveWithFullResponse: true
189 }),
190 new Promise(function(success, failure) {
191 req.session.destroy(function(err) {
192 if (err) {
193 var errorMsg = 'Error deleting session. Error: ' + err;
194 console.log(errorMsg);
195 success({
196 status: 'error',
197 message: errorMsg
198 });
199 }
200
201 var successMsg = 'Success deleting session';
202 console.log(successMsg);
203
204 success({
205 status: 'success',
206 message: successMsg
207 });
208 });
209 })
210 ]).then(function(result) {
211 // assume the session was deleted!
212 var message = 'Session was deleted.'
213 logAndRedirectToLogin(message, res, req);
214
215 }).catch(function(error) {
216 var message = 'Error deleting session or logging out. Error:' + error;
217 logAndRedirectToLogin(message, res, req);
218 });
219 });
220 }
221
222
223 module.exports = sessionsAPI;