public static bool Authorize(HttpRequestMessage request, RoleID[] roles) { string authToken = request.Headers.GetHeaderValue("authToken"); string activeUser = request.Headers.GetHeaderValue("username"); if (!string.IsNullOrEmpty(authToken) && !string.IsNullOrEmpty(activeUser)) { var database = new Database(); var session = database.AuthenticationTokens.Include(at => at.AssociatedVolunteer).Include(at => at.AssociatedVolunteer.Roles) .FirstOrDefault(at => at.Token.ToString() == authToken); if (session == null) return false; int[] roleIDs = roles.Select(r => (int) r).ToArray(); var lastAccessedTime = session.LastAccessedTime; //I have to do this so the auth token gets updated in the DB. Probably worth switching up what I'm doing here. database.SaveChanges(); var matchingRoles = session.AssociatedVolunteer.Roles.Where(r => roleIDs.Contains(r.ID)).ToList(); if (session.AssociatedVolunteer.Username == activeUser && matchingRoles.Count == roles.Length && lastAccessedTime > DateTime.UtcNow.AddMinutes(-AuthorizationOptions.AuthTokenTimeout) && lastAccessedTime < DateTime.UtcNow.AddSeconds(20) ) { return true; } } return false; }
public static AuthorizationResult Authorize(HttpRequestMessage request, RoleID[] roles) { string authToken = request.Headers.GetHeaderValue("authToken"); string activeUser = request.Headers.GetHeaderValue("username"); if (!string.IsNullOrEmpty(authToken) && !string.IsNullOrEmpty(activeUser)) { using (var database = new Database()) { var decodedAuthToken = Authorization.DecodeToken(authToken); if (decodedAuthToken == null) return AuthorizationResult.InvalidToken; if (decodedAuthToken.username != activeUser) return AuthorizationResult.MismatchedUser; if (decodedAuthToken.timeDiff > AuthorizationOptions.AuthTokenTimeout) return AuthorizationResult.ExpiredToken; //Valid token, need to check roles var dbRoles = database.RoleVolunteers .Where(rv => rv.Volunteer.Username == activeUser) .Include(rv => rv.Volunteer) .Select(rv => rv.Role.ID).ToArray(); if (roles.Select(r => (int)r).Intersect(dbRoles).Count() == roles.Length) return AuthorizationResult.Success; return AuthorizationResult.Unauthorized; } } return AuthorizationResult.InvalidRequest; }