/// <summary> /// Adds a login attempt to a user's log. /// </summary> /// <param name="userModel">UserModel with new Data.</param> /// <returns>Number of affected rows, should be 1.</returns> public LoginLog AddLogEntry(UserModel userModel) { ClientIdentifier clientIdentifier = Entities.ClientIdentifier.FirstOrDefault(x => x.UserName == userModel.UserName); LoginLog loginLog = new LoginLog { IpAdress = userModel.IpAdress, TimeStamp = DateTime.Now, UserAgent = userModel.UserAgent, Success = 0 }; if (clientIdentifier != null) { clientIdentifier.LastLogin = DateTime.Now; if (clientIdentifier.LoginLog == null) clientIdentifier.LoginLog = new Collection<LoginLog>(); clientIdentifier.LoginLog.Add(loginLog); } Entities.SaveChanges(); return loginLog; }
public string GetToken(UserModel user) { string token; try { token = AuthService.GenerateToken(user); } catch (ArgumentException e) { throw new WebFaultException(HttpStatusCode.NoContent); } catch (AccessViolationException ex) { throw new WebFaultException(HttpStatusCode.Forbidden); } return token; }
/// <summary> /// Confirms the registration and saves it to db. /// </summary> /// <param name="user">UserModel, with ClientId, Secret, UserName</param> /// <returns>Boolean if successful.</returns> public static bool ConfirmRegistration(UserModel user) { // try to get clientId from the RegistrationHandler-Dictonary String storedClientId = RegistrationHandler.GetClientId(user.UserName); if (storedClientId == null) return false; // Check if clientId is equals with the stored one if (!storedClientId.Equals(user.ClientId)) return false; Repository.CreateUser(new UserModel { ClientId = storedClientId, Secret = user.Secret, UserName = user.UserName, Status = 1 // set Status to registered }); user = null; return true; }
public string RequestRegister(UserModel json) { string resp = RegistrationService.RegisterRequest(json.UserName); if (resp == null) throw new WebFaultException(HttpStatusCode.NotAcceptable); return resp; }
public UserModel GetUserData(string userName) { var user = _repository.GetUserByUserName(userName); if (user == null) return null; // map only relevant data to model var userModel = new UserModel { UserName = user.UserName, DateTimeCreated = user.DateTimeCreated, DateTimeLogin = user.DateTimeLogin, Status = user.Status }; return userModel; }
public double GetCurrentRisk(UserModel user) { return _repository.CalculateRisk(user.UserName, user.UserAgent, user.IpAdress); }
//private readonly IRepository _repository = new MockRepository(); public void ConfirmRegister(UserModel json) { if (!RegistrationService.ConfirmRegistration(json)) throw new WebFaultException(HttpStatusCode.NotAcceptable); }
public string ValidateToken(UserModel json) { return AuthService.ValidateToken(json); }
public int SetStatusOfUser(UserModel json) { var user = _repository.GetUserByUserName(json.UserName); if (user == null) throw new WebFaultException(HttpStatusCode.BadRequest); user.Status = json.Status; return _repository.UpdateUser(user); }
/// <summary> /// Generates a one time token. /// </summary> /// <param name="userModel">UserModel</param> /// <returns>Token as string</returns> public static string GenerateToken(UserModel userModel) { UserModel user = Repository.GetUserByUserName(userModel.UserName); if (user == null) throw new ArgumentException("User not found."); if (user.Status != 1) throw new AccessViolationException(); if(!Repository.CalculateCurrentRisk(userModel.UserName, userModel.UserAgent, userModel.IpAdress)) throw new AccessViolationException(); RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); // random bytes byte[] token = new byte[RandomByteSize]; random.GetBytes(token); string tokenString = PasswordHash.ByteArrayToString(token); // user secret string secret = user.Secret; // Timestamp string timeStamp = Math.Abs((long)DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime()).TotalMilliseconds).ToString(); // convert to byte array byte[] timeBytes = PasswordHash.StringToByteArray(BitConverter.ToString(GetBytes(timeStamp)).Replace("-", "")); byte[] combinedArray = new byte[token.Length + timeBytes.Length]; for (int i = 0; i < combinedArray.Length; i++) { combinedArray[i] = i < token.Length ? token[i] : timeBytes[i - token.Length]; } var hexTime = BitConverter.ToString(GetBytes(timeStamp)).Replace("-", ""); var desc = tokenString + hexTime; // encrypt byte[] alpha = EncryptString(combinedArray, secret); // hashed token byte[] hashedToken = PasswordHash.PBKDF2(tokenString.ToUpper(), timeBytes, Iterations, HashByteSize); // convert to string string hashedTokenString = PasswordHash.ByteArrayToString(hashedToken); // save login attempt to log LoginLog loginLog = Repository.AddLogEntry(userModel); // add to waitlist AuthHandler.AddToWaitList(user.ClientId, hashedTokenString, loginLog); string result = PasswordHash.ByteArrayToString(alpha); // return alpha + epoch timestamp return result; }
/// <summary> /// Validates a token. /// </summary> /// <param name="userModel">UserModel</param> /// <returns>UserName, if token is valid</returns> public static string ValidateToken(UserModel userModel) { string clientID = userModel.ClientId; string token = userModel.Token; if (String.IsNullOrEmpty(clientID) || String.IsNullOrEmpty(token)) return String.Empty; // check for DoS to this clientID if (!Repository.CheckForDoS(clientID, userModel.IpAdress)) return String.Empty; // gets the old token from the waitlist string tokenFromWaitlist = AuthHandler.GetToken(clientID); LoginLog loginLog = AuthHandler.GetLoginLog(clientID); // if no value in waitlist if (String.IsNullOrEmpty(tokenFromWaitlist)) { // make log entry var newlog = new LoginLog() { MobileIpAdress = userModel.IpAdress, MobileUserAgent = userModel.UserAgent, Success = 0, TimeStamp = DateTime.Now, ClientIdentifier = null, UserId = null, ClientId = clientID }; Repository.CreateLog(newlog); return String.Empty; } if (loginLog == null || String.IsNullOrEmpty(tokenFromWaitlist)) return String.Empty; // Add properties to log loginLog.MobileIpAdress = userModel.IpAdress; loginLog.MobileUserAgent = userModel.UserAgent; Repository.SetLoginSuccess(loginLog, false); token = token.ToUpper(); // check token if (!token.Equals(tokenFromWaitlist)) return String.Empty; UserModel model = Repository.GetUserByClientId(clientID); if (model == null) return String.Empty; // Set log to success: true Repository.SetLoginSuccess(loginLog, true); AuthHandler.RemoveToken(clientID); return model.UserName; }
/// <summary> /// Converter. /// </summary> /// <param name="clientIdentifier">ClientIdentifier.</param> /// <returns>UserModel, or null if ClientIdentifier is null.</returns> private static UserModel ConvertToUserModel(ClientIdentifier clientIdentifier) { if (clientIdentifier == null) return null; var userModel = new UserModel { ClientId = clientIdentifier.ClientId.Trim(), Secret = clientIdentifier.Secret.Trim(), DateTimeCreated = clientIdentifier.DateCreated, DateTimeLogin = clientIdentifier.LastLogin, UserName = clientIdentifier.UserName.Trim() }; if (clientIdentifier.Status.HasValue) userModel.Status = clientIdentifier.Status.Value; return userModel; }
/// <summary> /// Converter. /// </summary> /// <param name="userModel">UserModel</param> /// <returns>ClientIdentigier, or null if UserModel is null.</returns> private static ClientIdentifier ConvertToClientIdentifier(UserModel userModel) { if (userModel == null) return null; return new ClientIdentifier { ClientId = userModel.ClientId, Status = userModel.Status, Secret = userModel.Secret, DateCreated = userModel.DateTimeCreated, LastLogin = userModel.DateTimeLogin, UserName = userModel.UserName, LoginLog = null }; }
/// <summary> /// Updates a User. /// </summary> /// <param name="userModel">UserModel with new Data.</param> /// <returns>Number of affected rows, should be 1.</returns> public int UpdateUser(UserModel userModel) { ClientIdentifier clientIdentifier = Entities.ClientIdentifier.FirstOrDefault(x => x.UserName == userModel.UserName); if (clientIdentifier != null) { clientIdentifier.LastLogin = DateTime.Now; clientIdentifier.ClientId = userModel.ClientId; clientIdentifier.Status = userModel.Status; clientIdentifier.Secret = userModel.Secret; } return Entities.SaveChanges(); }
/// <summary> /// Creates a new UserModel, or updates it, if it already exists. /// </summary> /// <param name="userModel">UserModel,</param> /// <returns>Number of affectes rows, should be 1.</returns> public int CreateUser(UserModel userModel) { // check if (Entities.ClientIdentifier.FirstOrDefault(x => x.UserName == userModel.UserName) != null) { return UpdateUser(userModel); } userModel.DateTimeCreated = DateTime.Now; Entities.ClientIdentifier.Add(ConvertToClientIdentifier(userModel)); return Entities.SaveChanges(); }