User management stuff

This commit is contained in:
Jamie.Rees 2016-10-25 17:31:59 +01:00
commit b851d77364
17 changed files with 232 additions and 94 deletions

View file

@ -40,13 +40,15 @@ using Nancy.Security;
using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Store;
using PlexRequests.Store.Repository;
using PlexRequests.UI.Models;
namespace PlexRequests.UI.Modules
{
public class LoginModule : BaseModule
{
public LoginModule(ISettingsService<PlexRequestSettings> pr, ICustomUserMapper m, IResourceLinker linker)
public LoginModule(ISettingsService<PlexRequestSettings> pr, ICustomUserMapper m, IResourceLinker linker, IRepository<UserLogins> userLoginRepo)
: base(pr)
{
UserMapper = m;
@ -101,6 +103,14 @@ namespace PlexRequests.UI.Modules
{
redirect = !string.IsNullOrEmpty(BaseUrl) ? $"/{BaseUrl}/search" : "/search";
}
userLoginRepo.Insert(new UserLogins
{
LastLoggedIn = DateTime.UtcNow,
Type = UserType.LocalUser,
UserId = userId.ToString()
});
return this.LoginAndRedirect(userId.Value, expiry, redirect);
};

View file

@ -232,10 +232,18 @@ namespace PlexRequests.UI.Modules
var plexMovies = Checker.GetPlexMovies();
var settings = await PrService.GetSettingsAsync();
var viewMovies = new List<SearchMovieViewModel>();
var counter = 0;
foreach (var movie in apiMovies)
{
var movieInfoTask = MovieApi.GetMovieInformation(movie.Id).ConfigureAwait(false); // TODO needs to be careful about this, it's adding extra time to search...
// https://www.themoviedb.org/talk/5807f4cdc3a36812160041f2
var imdbId = string.Empty;
if (counter <= 5) // Let's only do it for the first 5 items
{
var movieInfoTask = await MovieApi.GetMovieInformation(movie.Id).ConfigureAwait(false); // TODO needs to be careful about this, it's adding extra time to search...
// https://www.themoviedb.org/talk/5807f4cdc3a36812160041f2
imdbId = movieInfoTask.ImdbId;
counter++;
}
var viewMovie = new SearchMovieViewModel
{
Adult = movie.Adult,
@ -254,8 +262,7 @@ namespace PlexRequests.UI.Modules
VoteCount = movie.VoteCount
};
var canSee = CanUserSeeThisRequest(viewMovie.Id, settings.UsersCanViewOnlyOwnRequests, dbMovies);
var movieInfo = await movieInfoTask;
var plexMovie = Checker.GetMovie(plexMovies.ToArray(), movie.Title, movie.ReleaseDate?.Year.ToString(), movieInfo.ImdbId);
var plexMovie = Checker.GetMovie(plexMovies.ToArray(), movie.Title, movie.ReleaseDate?.Year.ToString(), imdbId);
if (plexMovie != null)
{
viewMovie.Available = true;

View file

@ -42,6 +42,8 @@ using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Helpers.Analytics;
using PlexRequests.Store;
using PlexRequests.Store.Repository;
using PlexRequests.UI.Models;
@ -52,7 +54,7 @@ namespace PlexRequests.UI.Modules
public class UserLoginModule : BaseModule
{
public UserLoginModule(ISettingsService<AuthenticationSettings> auth, IPlexApi api, ISettingsService<PlexSettings> plexSettings, ISettingsService<PlexRequestSettings> pr,
ISettingsService<LandingPageSettings> lp, IAnalytics a, IResourceLinker linker) : base("userlogin", pr)
ISettingsService<LandingPageSettings> lp, IAnalytics a, IResourceLinker linker, IRepository<UserLogins> userLogins) : base("userlogin", pr)
{
AuthService = auth;
LandingPageSettings = lp;
@ -60,13 +62,14 @@ namespace PlexRequests.UI.Modules
Api = api;
PlexSettings = plexSettings;
Linker = linker;
UserLogins = userLogins;
Get["UserLoginIndex", "/", true] = async (x, ct) =>
{
if (!string.IsNullOrEmpty(Username) || IsAdmin)
{
var url = Linker.BuildRelativeUri(Context, "SearchIndex").ToString();
return Response.AsRedirect(url);
return Response.AsRedirect(url);
}
var settings = await AuthService.GetSettingsAsync();
return View["Index", settings];
@ -82,11 +85,13 @@ namespace PlexRequests.UI.Modules
private IPlexApi Api { get; }
private IResourceLinker Linker { get; }
private IAnalytics Analytics { get; }
private IRepository<UserLogins> UserLogins { get; }
private static Logger Log = LogManager.GetCurrentClassLogger();
private async Task<Response> LoginUser()
{
var userId = string.Empty;
var dateTimeOffset = Request.Form.DateTimeOffset;
var username = Request.Form.username.Value;
Log.Debug("Username \"{0}\" attempting to login", username);
@ -135,6 +140,7 @@ namespace PlexRequests.UI.Modules
authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
Log.Debug("Friends list result = {0}", authenticated);
}
userId = signedIn.user.uuid;
}
}
else if (settings.UserAuthentication) // Check against the users in Plex
@ -147,6 +153,11 @@ namespace PlexRequests.UI.Modules
authenticated = true;
}
Log.Debug("Friends list result = {0}", authenticated);
if (authenticated)
{
// Get the user that is authenticated to store in the UserLogins
userId = GetUserIdIsInPlexFriends(username, plexSettings.PlexAuthToken);
}
}
else if (!settings.UserAuthentication) // No auth, let them pass!
{
@ -156,13 +167,13 @@ namespace PlexRequests.UI.Modules
if (authenticated)
{
UserLogins.Insert(new UserLogins { UserId = userId, Type = UserType.PlexUser, LastLoggedIn = DateTime.UtcNow });
Log.Debug("We are authenticated! Setting session.");
// Add to the session (Used in the BaseModules)
Session[SessionKeys.UsernameKey] = (string)username;
Session[SessionKeys.ClientDateTimeOffsetKey] = (int)dateTimeOffset;
}
Session[SessionKeys.ClientDateTimeOffsetKey] = (int)dateTimeOffset;
if (!authenticated)
{
var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex");
@ -214,6 +225,14 @@ namespace PlexRequests.UI.Modules
return allUsers != null && allUsers.Any(x => x.Title.Equals(username, StringComparison.CurrentCultureIgnoreCase));
}
private string GetUserIdIsInPlexFriends(string username, string authToken)
{
var users = Api.GetUsers(authToken);
var allUsers = users?.User?.Where(x => !string.IsNullOrEmpty(x.Title));
return allUsers?.Where(x => x.Title.Equals(username, StringComparison.CurrentCultureIgnoreCase)).Select(x => x.Id).FirstOrDefault();
}
private bool IsUserInDeniedList(string username, AuthenticationSettings settings)
{
return settings.DeniedUserList.Any(x => x.Equals(username, StringComparison.CurrentCultureIgnoreCase));

View file

@ -14,13 +14,14 @@ using PlexRequests.Core.Models;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Store;
using PlexRequests.Store.Repository;
using PlexRequests.UI.Models;
namespace PlexRequests.UI.Modules
{
public class UserManagementModule : BaseModule
{
public UserManagementModule(ISettingsService<PlexRequestSettings> pr, ICustomUserMapper m, IPlexApi plexApi, ISettingsService<PlexSettings> plex) : base("usermanagement", pr)
public UserManagementModule(ISettingsService<PlexRequestSettings> pr, ICustomUserMapper m, IPlexApi plexApi, ISettingsService<PlexSettings> plex, IRepository<UserLogins> userLogins) : base("usermanagement", pr)
{
#if !DEBUG
this.RequiresClaims(UserClaims.Admin);
@ -28,6 +29,7 @@ namespace PlexRequests.UI.Modules
UserMapper = m;
PlexApi = plexApi;
PlexSettings = plex;
UserLoginsRepo = userLogins;
Get["/"] = x => Load();
@ -43,6 +45,7 @@ namespace PlexRequests.UI.Modules
private ICustomUserMapper UserMapper { get; }
private IPlexApi PlexApi { get; }
private ISettingsService<PlexSettings> PlexSettings { get; }
private IRepository<UserLogins> UserLoginsRepo { get; }
private Negotiator Load()
{
@ -55,7 +58,8 @@ namespace PlexRequests.UI.Modules
var model = new List<UserManagementUsersViewModel>();
foreach (var user in localUsers)
{
model.Add(MapLocalUser(user));
var userDb = UserLoginsRepo.Get(user.UserGuid);
model.Add(MapLocalUser(user, userDb.LastLoggedIn));
}
var plexSettings = await PlexSettings.GetSettingsAsync();
@ -66,7 +70,7 @@ namespace PlexRequests.UI.Modules
foreach (var u in plexUsers.User)
{
var userDb = UserLoginsRepo.Get(u.Id);
model.Add(new UserManagementUsersViewModel
{
Username = u.Username,
@ -77,7 +81,8 @@ namespace PlexRequests.UI.Modules
PlexInfo = new UserManagementPlexInformation
{
Thumb = u.Thumb
}
},
LastLoggedIn = userDb.LastLoggedIn,
});
}
}
@ -105,7 +110,7 @@ namespace PlexRequests.UI.Modules
var user = UserMapper.CreateUser(model.Username, model.Password, model.Claims, new UserProperties { EmailAddress = model.EmailAddress });
if (user.HasValue)
{
return Response.AsJson(MapLocalUser(UserMapper.GetUser(user.Value)));
return Response.AsJson(MapLocalUser(UserMapper.GetUser(user.Value), DateTime.MinValue));
}
return Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not save user" });
@ -150,8 +155,8 @@ namespace PlexRequests.UI.Modules
userFound.UserProperties = ByteConverterHelper.ReturnBytes(currentProps);
var user = UserMapper.EditUser(userFound);
var retUser = MapLocalUser(user);
var dbUser = UserLoginsRepo.Get(user.UserGuid);
var retUser = MapLocalUser(user, dbUser.LastLoggedIn);
return Response.AsJson(retUser);
}
@ -224,7 +229,7 @@ namespace PlexRequests.UI.Modules
return Response.AsJson(retVal);
}
private UserManagementUsersViewModel MapLocalUser(UsersModel user)
private UserManagementUsersViewModel MapLocalUser(UsersModel user, DateTime lastLoggedIn)
{
var claims = ByteConverterHelper.ReturnObject<string[]>(user.Claims);
var claimsString = string.Join(", ", claims);
@ -240,7 +245,8 @@ namespace PlexRequests.UI.Modules
EmailAddress = userProps.EmailAddress,
Alias = userProps.UserAlias,
ClaimsArray = claims,
ClaimsItem = new List<UserManagementUpdateModel.ClaimsModel>()
ClaimsItem = new List<UserManagementUpdateModel.ClaimsModel>(),
LastLoggedIn = lastLoggedIn
};
// Add all of the current claims