forked from Ombi-app/Ombi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecurityExtensions.cs
327 lines (286 loc) · 12 KB
/
SecurityExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: SecurityExtensions.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using Nancy;
using Nancy.Linker;
using Nancy.Responses;
using Nancy.Security;
using Nancy.Session;
using Ombi.Core.Models;
using Ombi.Core.SettingModels;
using Ombi.Core.Users;
using Ombi.Helpers;
using Ombi.Helpers.Permissions;
using Ombi.Store.Models.Emby;
using Ombi.Store.Models.Plex;
using Ombi.Store.Repository;
namespace Ombi.Core
{
public class SecurityExtensions : ISecurityExtensions
{
public SecurityExtensions(IUserRepository userRepository, IResourceLinker linker, IExternalUserRepository<PlexUsers> plexUsers, ISettingsService<UserManagementSettings> umSettings,
IExternalUserRepository<EmbyUsers> embyUsers)
{
UserRepository = userRepository;
Linker = linker;
PlexUsers = plexUsers;
UserManagementSettings = umSettings;
EmbyUsers = embyUsers;
}
private IUserRepository UserRepository { get; }
private IResourceLinker Linker { get; }
private IExternalUserRepository<PlexUsers> PlexUsers { get; }
private IExternalUserRepository<EmbyUsers> EmbyUsers { get; }
private ISettingsService<UserManagementSettings> UserManagementSettings { get; }
public bool IsLoggedIn(NancyContext context)
{
var userName = context.Request.Session[SessionKeys.UsernameKey];
var realUser = false;
var plexUser = userName != null;
if (context.CurrentUser?.IsAuthenticated() ?? false)
{
realUser = true;
}
return realUser || plexUser;
}
public bool IsExternalUser(IUserIdentity user)
{
if (user == null)
{
return false;
}
var plexUser = PlexUsers.GetUserByUsername(user.UserName);
var embyUser = EmbyUsers.GetUserByUsername(user.UserName);
return plexUser != null || embyUser != null;
}
public bool IsNormalUser(IUserIdentity user)
{
if (user == null)
{
return false;
}
var dbUser = UserRepository.GetUserByUsername(user.UserName);
return dbUser != null;
}
/// <summary>
/// Gets the username this could be the alias! We should always use this method when getting the username
/// </summary>
/// <param name="username">The username.</param>
/// <param name="session"></param>
/// <returns>
/// <c>null</c> if we cannot find a user
/// </returns>
public string GetUsername(string username, ISession session)
{
var plexUser = PlexUsers.GetUserByUsername(username);
if (plexUser != null)
{
return !string.IsNullOrEmpty(plexUser.UserAlias) ? plexUser.UserAlias : plexUser.Username;
}
var embyUser = EmbyUsers.GetUserByUsername(username);
if (embyUser != null)
{
return !string.IsNullOrEmpty(embyUser.UserAlias) ? embyUser.UserAlias : embyUser.Username;
}
var dbUser = UserRepository.GetUserByUsername(username);
if (dbUser != null)
{
var userProps = ByteConverterHelper.ReturnObject<UserProperties>(dbUser.UserProperties);
return !string.IsNullOrEmpty(userProps.UserAlias) ? userProps.UserAlias : dbUser.UserName;
}
// could be a local user
var hasSessionKey = session[SessionKeys.UsernameKey] != null;
if (hasSessionKey)
{
return (string)session[SessionKeys.UsernameKey];
}
return string.Empty;
}
/// <summary>
/// Creates a hook to be used in a pipeline before a route handler to ensure
/// that the request was made by an authenticated user does not have the claims.
/// </summary>
/// <param name="perm">Claims the authenticated user needs to have</param>
/// <returns>Hook that returns an Unauthorized response if the user is not
/// authenticated or does have the claims, null otherwise</returns>
private Func<NancyContext, Response> DoesNotHavePermissions(int perm)
{
return ForbiddenIfNot(ctx =>
{
var permissions = GetPermissions(ctx.CurrentUser);
var result = permissions.HasFlag((Permissions)perm);
return !result;
});
}
public bool DoesNotHavePermissions(int perm, IUserIdentity currentUser)
{
return DoesNotHavePermissions((Permissions)perm, currentUser);
}
public bool DoesNotHavePermissions(Permissions perm, IUserIdentity currentUser)
{
var permissions = GetPermissions(currentUser);
var result = permissions.HasFlag(perm);
return !result;
}
public bool HasPermissions(IUserIdentity user, Permissions perm)
{
var permissions = GetPermissions(user);
return permissions.HasFlag(perm);
}
public bool HasPermissions(string userName, Permissions perm)
{
var permissions = GetPermissions(userName);
return permissions.HasFlag(perm);
}
public bool HasAnyPermissions(IUserIdentity user, params Permissions[] perm)
{
var permissions = GetPermissions(user);
foreach (var p in perm)
{
var result = permissions.HasFlag(p);
if (result)
{
return true;
}
}
return false;
}
public Response HasPermissionsRedirect(Permissions perm, NancyContext context, string routeName, HttpStatusCode code)
{
var url = Linker.BuildRelativeUri(context, routeName);
var response = ForbiddenIfNot(ctx =>
{
var permissions = GetPermissions(ctx.CurrentUser);
var result = permissions.HasFlag(perm);
return result;
});
var r = response(context);
return r.StatusCode == code
? new RedirectResponse($"{url.ToString()}?redirect={context.Request.Path}")
: null;
}
public Response HasAnyPermissionsRedirect(NancyContext context, string routeName, HttpStatusCode code, params Permissions[] perm)
{
var url = Linker.BuildRelativeUri(context, routeName);
var response = ForbiddenIfNot(ctx =>
{
var permissions = GetPermissions(ctx.CurrentUser);
var hasPermission = false;
foreach (var p in perm)
{
var result = permissions.HasFlag(p);
if (result)
{
hasPermission = true;
}
}
return hasPermission;
});
var r = response(context);
return r.StatusCode == code
? new RedirectResponse(url.ToString())
: null;
}
public Response AdminLoginRedirect(Permissions perm, NancyContext context)
{
// This will redirect us to the Login Page if we don't have the correct permission passed in (e.g. Admin with Http 403 status code).
return HasPermissionsRedirect(perm, context, "LocalLogin", HttpStatusCode.Forbidden);
}
public Response AdminLoginRedirect(NancyContext context, params Permissions[] perm)
{
// This will redirect us to the Login Page if we don't have the correct permission passed in (e.g. Admin with Http 403 status code).
return HasAnyPermissionsRedirect(context, "LocalLogin", HttpStatusCode.Forbidden, perm);
}
// BELOW IS A COPY FROM THE SecurityHooks CLASS!
/// <summary>
/// Creates a hook to be used in a pipeline before a route handler to ensure that
/// the request satisfies a specific test.
/// </summary>
/// <param name="test">Test that must return true for the request to continue</param>
/// <returns>Hook that returns an Forbidden response if the test fails, null otherwise</returns>
public Func<NancyContext, Response> ForbiddenIfNot(Func<NancyContext, bool> test)
{
return HttpStatusCodeIfNot(HttpStatusCode.Forbidden, test);
}
/// <summary>
/// Creates a hook to be used in a pipeline before a route handler to ensure that
/// the request satisfies a specific test.
/// </summary>
/// <param name="statusCode">HttpStatusCode to use for the response</param>
/// <param name="test">Test that must return true for the request to continue</param>
/// <returns>Hook that returns a response with a specific HttpStatusCode if the test fails, null otherwise</returns>
public Func<NancyContext, Response> HttpStatusCodeIfNot(HttpStatusCode statusCode, Func<NancyContext, bool> test)
{
return ctx =>
{
Response response = new Response
{
StatusCode = HttpStatusCode.OK
};
if (!test(ctx))
{
response = new Response
{
StatusCode = statusCode
};
}
return response;
};
}
private Permissions GetPermissions(IUserIdentity user)
{
return GetPermissions(user?.UserName);
}
private Permissions GetPermissions(string userName)
{
if (string.IsNullOrEmpty(userName))
{
// Username without auth
var s = UserManagementSettings.GetSettings();
return (Permissions)UserManagementHelper.GetPermissions(s);
}
var dbUser = UserRepository.GetUserByUsername(userName);
if (dbUser != null)
{
var permissions = (Permissions)dbUser.Permissions;
return permissions;
}
var plexUser = PlexUsers.GetUserByUsername(userName);
if (plexUser != null)
{
var permissions = (Permissions)plexUser.Permissions;
return permissions;
}
var embyUsers = EmbyUsers.GetUserByUsername(userName);
if (embyUsers != null)
{
return (Permissions) embyUsers.Permissions;
}
return 0;
}
}
}