Project UI updates and bug fixes
[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
35 function logAndReject(mesg, reject) {
36 res.errorMessage = {
37 error: mesg
38 }
39 console.log(mesg);
40 reject(res);
41 }
42
43 function logAndRedirectToLogin(mesg, res, req) {
44 console.log(mesg);
45 res.redirect('login.html?api_server=' + req.query['api_server']);
46 res.end();
47 }
48
49 sessionsAPI.create = function(req, res) {
50 var api_server = req.query["api_server"];
51 var uri = utils.confdPort(api_server);
52 var login_url = uri + APIVersion + '/api/login';
53 var project_url = uri + APIVersion + '/api/operational/project';
54 var authorization_header_string = 'Basic ' + base64.encode(req.body['username'] + ':' + req.body['password']);
55 return new Promise(function(resolve, reject) {
56 Promise.all([
57 rp({
58 url: login_url,
59 method: 'POST',
60 headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
61 'Authorization': authorization_header_string
62 }),
63 forever: constants.FOREVER_ON,
64 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
65 resolveWithFullResponse: true
66 }),
67 rp({
68 url: project_url,
69 method: 'GET',
70 headers: _.extend({}, constants.HTTP_HEADERS.accept.collection, {
71 'Authorization': authorization_header_string
72 }),
73 forever: constants.FOREVER_ON,
74 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
75 resolveWithFullResponse: true
76 })
77
78 ]).then(function(results) {
79 // results[0].statusCode => 200/201
80 // results[1].body.collection['rw-project:project'] => List of projects OR 204 with no content
81 if (results[0].statusCode != constants.HTTP_RESPONSE_CODES.SUCCESS.OK) {
82 var errorMsg = 'Invalid credentials provided!';
83 logAndRedirectToLogin(errorMsg, res, req);
84 return;
85 }
86
87 var username = req.body['username'];
88 var project_list_for_user = [];
89
90 if (results[1].statusCode == constants.HTTP_RESPONSE_CODES.SUCCESS.NO_CONTENT) {
91 console.log('No projects added or user ', username ,' not privileged to view projects.');
92 } else {
93 // go through projects and get list of projects that this user belongs to.
94 // pick first one as default project?
95
96 var projects = JSON.parse(results[1].body).collection['rw-project:project'];
97 projects && projects.map(function(project) {
98 project['project-config'] &&
99 project['project-config']['user'] &&
100 project['project-config']['user'].map(function(user) {
101 if (user['user-name'] == username) {
102 project_list_for_user.push(project.name);
103 }
104 });
105 });
106
107 req.session.projectId = (project_list_for_user.length > 0) && project_list_for_user.sort() && project_list_for_user[0];
108 }
109
110 req.session.authorization = authorization_header_string;
111 req.session.loggedIn = true;
112 req.session.userdata = {
113 username: username,
114 // project: req.session.projectId
115 };
116 var successMsg = 'User =>' + username + ' successfully logged in.';
117 successMsg += req.session.projectId ? 'Project =>' + req.session.projectId + ' set as default.' : '';
118
119 console.log(successMsg);
120
121 var response = {
122 statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.CREATED,
123 data: JSON.stringify({
124 status: successMsg
125 })
126 };
127 resolve(response);
128
129 }).catch(function(error) {
130 // Something went wrong - Redirect to /login
131 var errorMsg = 'Error logging in or getting list of projects. Error: ' + error;
132 console.log(errorMsg);
133 logAndRedirectToLogin(errorMsg, res, req);
134 });
135 })
136 };
137
138 sessionsAPI.addProjectToSession = function(req, res) {
139 return new Promise(function(resolve, reject) {
140 if (req.session && req.session.loggedIn == true) {
141 req.session.projectId = req.params.projectId;
142 var successMsg = 'Added project' + projectId + ' to session' + req.sessionID;
143 console.log(successMsg);
144
145 return resolve ({
146 statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK,
147 data: JSON.stringify({
148 status: successMsg
149 })
150 });
151 }
152
153 var errorMsg = 'Session does not exist or not logged in';
154 logAndReject(errorMsg, reject);
155 });
156 }
157
158 sessionsAPI.delete = function(req, res) {
159 var api_server = req.query["api_server"];
160 var uri = utils.confdPort(api_server);
161 var url = uri + '/api/logout';
162 return new Promise(function(resolve, reject) {
163 Promise.all([
164 rp({
165 url: url,
166 method: 'POST',
167 headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
168 'Authorization': req.session.authorization
169 }),
170 forever: constants.FOREVER_ON,
171 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
172 resolveWithFullResponse: true
173 }),
174 new Promise(function(success, failure) {
175 req.session.destroy(function(err) {
176 if (err) {
177 var errorMsg = 'Error deleting session. Error: ' + err;
178 console.log(errorMsg);
179 success({
180 status: 'error',
181 message: errorMsg
182 });
183 }
184
185 var successMsg = 'Success deleting session';
186 console.log(successMsg);
187
188 success({
189 status: 'success',
190 message: successMsg
191 });
192 });
193 })
194 ]).then(function(result) {
195 // assume the session was deleted!
196 var message = 'Session was deleted.'
197 logAndRedirectToLogin(message, res, req);
198
199 }).catch(function(error) {
200 var message = 'Error deleting session or logging out. Error:' + error;
201 logAndRedirectToLogin(message, res, req);
202 });
203 });
204 }
205
206
207 module.exports = sessionsAPI;