Beispiel #1
0
        public static void GenerateNewAuthToken(LoginStatusTokens tokens)
        {
            Random rand = new Random();

            byte[] loginToken = new byte[64];
            rand.NextBytes(loginToken);
            tokens.AuthToken = MysqlDataConvertingUtil.ConvertToHexString(loginToken);
            DateTime now = DateTime.UtcNow;

            now = now.AddHours(.5);
            tokens.AuthTokenExpiration = now.ToString();
        }
Beispiel #2
0
        public static LoginStatusTokens ExtractLoginTokens(OverallUser userIn)
        {
            string loggedTokensJson = userIn.LoginStatusTokens;

            loggedTokensJson = loggedTokensJson.Replace("\\\"", "\"");
            byte[]       tokens = Encoding.UTF8.GetBytes(loggedTokensJson);
            MemoryStream stream = new MemoryStream(tokens);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(LoginStatusTokens));
            LoginStatusTokens          ret        = serializer.ReadObject(stream) as LoginStatusTokens;

            return(ret);
        }
Beispiel #3
0
        public static bool AuthTokenValid(OverallUser databaseUser, string authToken)
        {
            byte[] convertedText = Encoding.UTF8.GetBytes(databaseUser.LoginStatusTokens);
            DataContractJsonSerializer loggedTokenSerializer = new DataContractJsonSerializer(typeof(LoginStatusTokens));
            LoginStatusTokens          dbTokens = loggedTokenSerializer.ReadObject(new MemoryStream(convertedText)) as LoginStatusTokens;

            if (dbTokens == null)
            {
                throw new ArgumentException("database user had an invalid entry for logged tokens");
            }
            if (!authToken.Equals(dbTokens.AuthToken))
            {
                return(false);
            }
            DateTime dbExpiration = DateTime.Parse(dbTokens.AuthTokenExpiration);

            return(DateTime.UtcNow.CompareTo(dbExpiration) < 0);
        }
Beispiel #4
0
        /// <summary>
        /// Request for a user to log in using their email and password. Documention is found in the Web API Enumeration file
        /// in the /RepairJob/Requirements tab, starting at row 21
        /// </summary>
        /// <param name="ctx">The HttpListenerContext to respond to</param>
        public void HandlePutRequest(HttpListenerContext ctx)
        {
            try
            {
                #region Input Validation
                if (!ctx.Request.HasEntityBody)
                {
                    WriteBodyResponse(ctx, 400, "No Body", "Request lacked a body");
                    return;
                }
                string           reqString = new StreamReader(ctx.Request.InputStream).ReadToEnd();
                UserLoginRequest req       = JsonDataObjectUtil <UserLoginRequest> .ParseObject(reqString);

                if (req == null)
                {
                    WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format");
                    return;
                }
                if (!ValidateLoginRequest(req))
                {
                    UserCheckLoginStatusRequest req2 = JsonDataObjectUtil <UserCheckLoginStatusRequest> .ParseObject(reqString);

                    if (req2 != null && ValidateCheckLoginRequest(req2))
                    {
                        HandleCheckLoginRequest(ctx, req2);
                        return;
                    }
                    WriteBodyResponse(ctx, 400, "Incorrect Format", "Not all fields of the request were filled");
                    return;
                }
                #endregion

                MySqlDataManipulator connection = new MySqlDataManipulator();
                using (connection)
                {
                    bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString());
                    if (!res)
                    {
                        WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed");
                        return;
                    }
                    #region Action Handling
                    var users = connection.GetUsersWhere(" Email = \"" + req.Email + "\"");
                    if (users.Count == 0)
                    {
                        WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server");
                        return;
                    }
                    if (!UserVerificationUtil.VerifyLogin(users[0], req.Email, req.Password))
                    {
                        WriteBodyResponse(ctx, 401, "Unauthorized", "Email or password was incorrect");
                        return;
                    }
                    OverallUser       loggedInUser = users[0];
                    LoginStatusTokens tokens       = UserVerificationUtil.ExtractLoginTokens(loggedInUser);
                    UserVerificationUtil.GenerateNewLoginToken(tokens);
                    if (!connection.UpdateUsersLoginToken(loggedInUser, tokens))
                    {
                        WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Failed to write login token to database");
                        return;
                    }
                    JsonDictionaryStringConstructor retConstructor = new JsonDictionaryStringConstructor();
                    retConstructor.SetMapping("token", tokens.LoginToken);
                    retConstructor.SetMapping("userId", loggedInUser.UserId);
                    retConstructor.SetMapping("accessLevel", loggedInUser.AccessLevel);
                    WriteBodyResponse(ctx, 200, "OK", retConstructor.ToString(), "application/json");
                    #endregion
                }
            }
            catch (HttpListenerException)
            {
                //HttpListeners dispose themselves when an exception occurs, so we can do no more.
            }
            catch (Exception e)
            {
                WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Request for a user to receive authentication to make edits to content they have access to. Documention is found in the Web API Enumeration file
        /// in the /RepairJob/Requirements tab, starting at row 21
        /// </summary>
        /// <param name="ctx">The HttpListenerContext to respond to</param>
        private void HandlePutRequest(HttpListenerContext ctx)
        {
            try
            {
                #region Input Validation
                if (!ctx.Request.HasEntityBody)
                {
                    WriteBodyResponse(ctx, 400, "No Body", "Request lacked a body");
                    return;
                }
                string reqString          = new StreamReader(ctx.Request.InputStream).ReadToEnd();
                AuthenticationRequest req = JsonDataObjectUtil <AuthenticationRequest> .ParseObject(reqString);

                if (req == null)
                {
                    WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format");
                    return;
                }
                if (!ValidateAuthenticationRequest(req))
                {
                    AuthenticationCheckRequest req2 = JsonDataObjectUtil <AuthenticationCheckRequest> .ParseObject(reqString);

                    if (req2 != null && ValidateAuthCheckRequest(req2))
                    {
                        HandleAuthCheckRequest(ctx, req2);
                        return;
                    }
                    WriteBodyResponse(ctx, 400, "Incorrect Format", "Not all fields of the request were filled");
                    return;
                }
                #endregion

                MySqlDataManipulator connection = new MySqlDataManipulator();
                using (connection)
                {
                    bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString());
                    if (!res)
                    {
                        WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed");
                        return;
                    }
                    #region User Validation
                    var user = connection.GetUserById(req.UserId);
                    if (user == null)
                    {
                        WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server");
                        return;
                    }
                    if (!UserVerificationUtil.LoginTokenValid(user, req.LoginToken))
                    {
                        WriteBodyResponse(ctx, 401, "Unauthorized", "Login Token is incorrect or expired");
                        return;
                    }
                    if (!UserVerificationUtil.VerifyAuthentication(user, req.SecurityQuestion, req.SecurityAnswer))
                    {
                        WriteBodyResponse(ctx, 401, "Unauthorized", "Security Answer was incorrect");
                        return;
                    }
                    #endregion

                    #region Action Handling
                    LoginStatusTokens tokens = UserVerificationUtil.ExtractLoginTokens(user);
                    UserVerificationUtil.GenerateNewAuthToken(tokens);
                    if (!connection.UpdateUsersLoginToken(user, tokens))
                    {
                        WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Failed to write login token to database");
                        return;
                    }
                    JsonDictionaryStringConstructor retConstructor = new JsonDictionaryStringConstructor();
                    retConstructor.SetMapping("token", tokens.AuthToken);
                    WriteBodyResponse(ctx, 200, "OK", retConstructor.ToString());
                    #endregion
                }
            }
            catch (HttpListenerException)
            {
                //HttpListeners dispose themselves when an exception occurs, so we can do no more.
            }
            catch (Exception e)
            {
                WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message);
            }
        }