static void PushUserData(String[] req_UserData, SqlConnection connection) { Console.WriteLine("Push User Data"); GenerateResponses Gr = new GenerateResponses(); GenerateHash GH = new GenerateHash(); string email = req_UserData[0]; string uname = req_UserData[1]; string pswrd = req_UserData[2]; string fname = req_UserData[3]; string dptmt = req_UserData[4]; string salt = GH.GenerateSalt(); Console.WriteLine("pswrd" + pswrd); pswrd = GH.Generate(pswrd + salt); connection.Open(); SqlCommand cmd = new SqlCommand("insert into users (username, password_hash, salt, first_name, department, email)" + "values(@uname,@pswrd, @salt, @fname, @dptmt, @email)", connection); cmd.Parameters.AddWithValue("@uname", uname); cmd.Parameters.AddWithValue("@pswrd", pswrd); cmd.Parameters.AddWithValue("@salt", salt); cmd.Parameters.AddWithValue("@fname", fname); cmd.Parameters.AddWithValue("@dptmt", dptmt); cmd.Parameters.AddWithValue("@email", email); int rowsaffected = cmd.ExecuteNonQuery(); Console.WriteLine(rowsaffected); connection.Close(); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request. - Registration"); GenerateResponses Gr = new GenerateResponses(); string uname = req.Query["uname"]; string pswrd = req.Query["pswrd"]; string email = req.Query["email"]; string fname = req.Query["fname"]; string dptmt = req.Query["dptmt"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); email = email ?? data?.email; uname = uname ?? data?.uname; pswrd = pswrd ?? data?.pswrd; fname = fname ?? data?.fname; dptmt = dptmt ?? data?.dptmt; //Check if User already exists bool DoesUserExist = CheckIfUserAlreadyExist(email); if (DoesUserExist) { return(Gr.Forbidden("An account with the email already exists")); } //Check if Username is taken bool IsUserNameTaken = CheckIfUserNameAlreadyExist(uname); if (IsUserNameTaken) { return(Gr.Forbidden("User name already exits, please enter a different one")); } //Initialize OTPGen Class OTPGen gen = new OTPGen(uname, email); gen.GenerateOTP(); //Generate OTP var EmailSentAction = gen.SendOTP(); //Send Email gen.PushHash(); //Push OTP hash to Database if (EmailSentAction.Equals(1)) { return(Gr.RequestTimeOut("Error email cannot be sent")); } return(Gr.OkResponse("Ok")); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string session_token = req.Query["token"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); session_token = session_token ?? data?.token; DatabaseConnector DBConn = new DatabaseConnector(); SqlConnection connection = DBConn.connector("Users"); GenerateResponses Gr = new GenerateResponses(); SqlCommand cmd = new SqlCommand("select CA, SI, ER from Users where session_token=@token", connection); cmd.Parameters.AddWithValue("@token", session_token); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); try { connection.Open(); adapter.Fill(dt); connection.Close(); } catch (Exception e) { Gr.InternalServerError(e.ToString()); } DataSet ds = new DataSet(); ds.Tables.Add(dt); string dsXML = ds.GetXml(); return(Gr.OkResponse(dsXML)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request. - Logout"); string session_token = req.Query["token"]; //Get Session token from POST string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); session_token = session_token ?? data?.token; //get the token if serialized GenerateResponses Gr = new GenerateResponses(); if (string.IsNullOrEmpty(session_token)) { Gr.BadRequest("Token Empty"); } try { DatabaseConnector DBconn = new DatabaseConnector(); //Create object to connect to Database SqlConnection connection = DBconn.connector("Users"); //connect to User database //Command to delete tokens which are expired SqlCommand command = new SqlCommand("update Users set session_token=null where session_token=@token", connection); //Add value to the token command.Parameters.AddWithValue("@token", session_token); connection.Open(); command.ExecuteNonQuery(); connection.Close(); return(Gr.OkResponse("Token invalidated")); //Invalidate Token on logout }catch (Exception e) { Console.WriteLine(e.ToString()); return(Gr.BadRequest("Token Not invalidated")); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string token = req.Query["token"]; string Leave_ID = req.Query["LeaveID"]; GenerateResponses Gr = new GenerateResponses(); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); token = token ?? data?.token; Leave_ID = Leave_ID ?? data?.LeaveID; Console.WriteLine(Leave_ID); //update leavapplication set leave_status='A' where leave_id in ($values); DatabaseConnector DBConn = new DatabaseConnector(); SqlConnection connection = DBConn.connector("Users"); connection.Open(); SqlCommand UpdateLeaveStatus = new SqlCommand("update leaveapplication set leave_status='A' where leave_id=@Leave_ID", connection); UpdateLeaveStatus.Parameters.AddWithValue("@Leave_ID", Leave_ID); SqlCommand GetDaysAndType = new SqlCommand("select no_of_days, leave_type from leaveapplication where leave_id=@Leave_ID", connection); GetDaysAndType.Parameters.AddWithValue("@Leave_ID", Leave_ID); SqlCommand GetUserName = new SqlCommand("select username from leaveapplication where leave_id=@LeaveID", connection); GetUserName.Parameters.AddWithValue("@LeaveID", Leave_ID); UpdateLeaveStatus.ExecuteNonQuery(); SqlDataReader reader = GetDaysAndType.ExecuteReader(); string days, type; days = type = null; while (reader.Read()) { days = reader[0].ToString(); type = reader[1].ToString(); } reader.Close(); Console.WriteLine("Days and Types Done"); reader = GetUserName.ExecuteReader(); string uname, email; uname = email = null; while (reader.Read()) { uname = reader[0].ToString(); } reader.Close(); SqlCommand getEmailOfUser = new SqlCommand("select email from Users where username=@uname", connection); getEmailOfUser.Parameters.AddWithValue("@uname", uname); reader = getEmailOfUser.ExecuteReader(); while (reader.Read()) { email = reader[0].ToString(); } reader.Close(); switch (type) { case "CA": SqlCommand CACmd = new SqlCommand("update Users set CA=CA-@days where username=@uname", connection); CACmd.Parameters.AddWithValue("@days", days); CACmd.Parameters.AddWithValue("@uname", uname); Console.WriteLine(CACmd.CommandText.ToString()); CACmd.ExecuteNonQuery(); break; case "SI": SqlCommand SICmd = new SqlCommand("update Users set SI=SI-@days where username=@uname", connection); SICmd.Parameters.AddWithValue("@days", days); SICmd.Parameters.AddWithValue("@uname", uname); Console.WriteLine("SI"); SICmd.ExecuteNonQuery(); break; case "ER": SqlCommand ERCmd = new SqlCommand("update Users set ER=ER-@days where username=@uname", connection); ERCmd.Parameters.AddWithValue("@days", days); ERCmd.Parameters.AddWithValue("@uname", uname); Console.WriteLine("ER"); ERCmd.ExecuteNonQuery(); break; default: Gr.InternalServerError(Gr.INTSRE); break; } connection.Close(); _ = await SendEmail(email, uname); return(Gr.OkResponse(Gr.OKRESP)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string token = req.Query["token"]; string uname = null; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); token = token ?? data?.token; Console.WriteLine(token); DatabaseConnector conn = new DatabaseConnector(); SqlConnection connection = conn.connector("Users"); SqlDataReader reader; GenerateResponses Gr = new GenerateResponses(); if (connection == null) { Gr.InternalServerError("Internal Server Error"); } try { connection.Open(); SqlCommand cmd = new SqlCommand("select username from Users where session_token=@token", connection); cmd.Parameters.AddWithValue("@token", token); reader = cmd.ExecuteReader(); while (reader.Read()) { uname = reader[0].ToString(); } connection.Close(); }catch (Exception e) { Gr.InternalServerError(e.ToString()); } SqlCommand cmd_1 = new SqlCommand("select leave_id, username, from_date, to_date, no_of_days, reason, leave_type, leave_status from leaveapplication where username=@uname", connection); cmd_1.Parameters.AddWithValue("@uname", uname); SqlDataAdapter adapter = new SqlDataAdapter(cmd_1); DataTable dt = new DataTable(); try { connection.Open(); adapter.Fill(dt); connection.Close(); }catch (Exception e) { Gr.InternalServerError(e.ToString()); } DataSet ds = new DataSet(); ds.Tables.Add(dt); string dsXML = ds.GetXml(); Console.WriteLine(dsXML); return(Gr.OkResponse(dsXML)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { GenerateResponses Gr = new GenerateResponses(); log.LogInformation("C# HTTP trigger function processed a request."); string session_token = req.Query["token"]; string dptmt = null; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); session_token = session_token ?? data?.token; DatabaseConnector DBConn = new DatabaseConnector(); SqlConnection connection = DBConn.connector("Users"); SqlCommand cmd = new SqlCommand("select department from Users where session_token=@token", connection); cmd.Parameters.AddWithValue("@token", session_token); DataTable dt = new DataTable(); try { connection.Open(); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { dptmt = rdr[0].ToString(); } rdr.Close(); connection.Close(); //select * from leaveapplication where leave_id LIKE '<department>%' Console.WriteLine(dptmt); SqlCommand cmd_1 = new SqlCommand("select leave_id, username, from_date, to_date, no_of_days, reason, leave_status from leaveapplication where leave_id LIKE @dpt and leave_status='NA'", connection); cmd_1.Parameters.AddWithValue("@dpt", dptmt + "%"); Console.WriteLine(cmd_1.CommandText.ToString()); SqlDataAdapter DataAdapter = new SqlDataAdapter(cmd_1); connection.Open(); DataAdapter.Fill(dt); connection.Close(); } catch (Exception e) { Console.WriteLine(e.Message); return(Gr.InternalServerError(Gr.INTSRE)); } DataSet ds = new DataSet(); ds.Tables.Add(dt); string dsXML = ds.GetXml(); return(Gr.OkResponse(dsXML)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string token = req.Query["token"]; // Get token from post data, token from post data string token_in_database = null; //token in database //deserialize and read string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); token = token ?? data?.token; DatabaseConnector conn = new DatabaseConnector(); SqlConnection connection = conn.connector("Users"); GenerateResponses Gr = new GenerateResponses(); connection.Open(); //check if token exists SqlCommand cmd = new SqlCommand("select session_token from Users where session_token=@token", connection); cmd.Parameters.AddWithValue("@token", token); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { token_in_database = rdr[0].ToString(); //get token value in database } connection.Close(); if (token_in_database == token) //check if the tokens match { //If tokens match, check if the token is valid Token tk = new Token(); bool isValid = tk.IsTokenValid(token); if (!isValid) //If Token isn't valid remove token { if (DeleteTokenFromDataBase(token, connection)) { return(Gr.NotAcceptable("Token Expired")); } else { return(Gr.InternalServerError("Internal Server error")); } } else //Valid token { return(Gr.OkResponse("Valid Token")); } } else //If token doesn't match remove the token from database { if (DeleteTokenFromDataBase(token, connection)) { return(Gr.NotAcceptable("Invalid Token")); } else { return(Gr.InternalServerError("Internal Server error")); //If Internal server error occurs } } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request. - Apply"); GenerateResponses Gr = new GenerateResponses(); string s_From = req.Query["from"]; string s_To = req.Query["to"]; string Reason = req.Query["reason"]; string Session_Token = req.Query["token"]; string Type = req.Query["type"]; string uname = null; string department = null; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); s_From = s_From ?? data?.from; s_To = s_To ?? data?.to; DateTime From = DateTime.ParseExact(s_From, "dd/MM/yyyy", null); DateTime To = DateTime.ParseExact(s_To, "dd/MM/yyyy", null); Reason = Reason ?? data?.reason; Session_Token = Session_Token ?? data?.token; Type = Type ?? data?.type; DatabaseConnector DBconn = new DatabaseConnector(); SqlConnection connection = DBconn.connector("Users"); GenerateHash GH = new GenerateHash(); SqlDataReader reader; Session_Token = Session_Token.Replace(" ", ""); SqlCommand command_Retrieve_Uname_Dept = new SqlCommand("select username, department from Users where session_token=@token", connection); command_Retrieve_Uname_Dept.Parameters.AddWithValue("@token", Session_Token); connection.Open(); Console.WriteLine("From" + From.ToShortDateString()); reader = command_Retrieve_Uname_Dept.ExecuteReader(); while (reader.Read()) { uname = reader[0].ToString(); department = reader[1].ToString(); } connection.Close(); if (string.IsNullOrEmpty(uname) || string.IsNullOrEmpty(department)) { return(Gr.InternalServerError(InternalServerError)); } var LeaveDays = (To - From).TotalDays; var LeaveID = department + GH.GenerateSalt(); connection.Open(); s_From = From.ToShortDateString(); s_To = To.ToShortDateString(); SqlCommand command_Push_Data_Into_Leave = new SqlCommand("insert into leaveapplication(leave_id, from_date, to_date, no_of_days, reason, leave_type, username) values (@LeaveID, @From, @To, @Days, @Reason, @Type, @uname)", connection); command_Push_Data_Into_Leave.Parameters.AddWithValue("@LeaveID", LeaveID); command_Push_Data_Into_Leave.Parameters.AddWithValue("@From", s_From); command_Push_Data_Into_Leave.Parameters.AddWithValue("@To", s_To); command_Push_Data_Into_Leave.Parameters.AddWithValue("@Days", LeaveDays); command_Push_Data_Into_Leave.Parameters.AddWithValue("@Reason", Reason); command_Push_Data_Into_Leave.Parameters.AddWithValue("@Type", Type); command_Push_Data_Into_Leave.Parameters.AddWithValue("@uname", uname); command_Push_Data_Into_Leave.ExecuteNonQuery(); connection.Close(); return(Gr.OkResponse("Ok")); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); Token tk_1 = new Token(); tk_1.GenerateToken(); string uname = req.Query["uname"]; // get username string pswrd = req.Query["pswrd"]; // get password string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); uname = uname ?? data?.uname; pswrd = pswrd ?? data?.pswrd; string username = null; string pswrd_hash = null; string salt = null; string flag = null; GenerateResponses Gr = new GenerateResponses(); // Initializing response generator SqlDataReader reader; //Sql Data Reaeder byte[] Hash; // Store hash bytes SHA256 sha256 = SHA256.Create(); // SHA256 generator Encoding enc = Encoding.UTF8; // Encoding method StringBuilder hashbuilder = new StringBuilder(); // hash string builder //check if uname or pswrd is null if (string.IsNullOrEmpty(uname) || string.IsNullOrEmpty(pswrd)) { return(new BadRequestObjectResult("Password or Username Empty")); } DatabaseConnector DB_Con = new DatabaseConnector(); //Object for database connector SqlConnection connection = DB_Con.connector("Users"); //Returns a DB connection //If connection is not established, send internal server error if (connection == null) { return(Gr.InternalServerError("Internal server error cannot connect to Database")); // Ends if connection to database cannot be established } connection.Open(); // Open connection to database // SQL query to get username SqlCommand sqlCommand = new SqlCommand("select username, password_hash, salt, flag from Users where username=@uname", connection); sqlCommand.Parameters.AddWithValue("@uname", uname); reader = sqlCommand.ExecuteReader(); // Execute query and read data // Get username and password while (reader.Read()) { username = reader[0].ToString(); pswrd_hash = reader[1].ToString(); salt = reader[2].ToString(); flag = reader[3].ToString(); } connection.Close(); // Close connection to database Hash = sha256.ComputeHash(enc.GetBytes(pswrd + salt)); // Compute SHA256 hash for password // Convert each value in the hash byte to hex and put inside hashbuilder foreach (var h in Hash) { hashbuilder.Append(h.ToString("x2")); } // get the SHA256 hex for the hash pswrd = hashbuilder.ToString(); // Check if username is empty if (string.IsNullOrEmpty(username)) { return(Gr.BadRequest("Entered Username doesn't exist")); } // Check the password with password hash and generate token if (pswrd == pswrd_hash) { Token tk = new Token(); // Init token class string token = tk.GenerateToken(); // Generate token and store //bool token_val = tk.IsTokenValid(token); // check if token is valid DatabaseConnector DBConn = new DatabaseConnector(); SqlConnection conn = DBConn.connector("Users"); // SqlCommand cmd = new SqlCommand("update Users set session_token=@token where username=@uname ", conn); cmd.Parameters.AddWithValue("@uname", username); cmd.Parameters.AddWithValue("@token", token); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); string[] DataToReturn = { token.ToString(), flag.ToString() }; var json = JsonConvert.SerializeObject(DataToReturn); return(Gr.OkResponse(json)); // return token value if token is valid } else { return(Gr.BadRequest("username or password incorrect")); // return if password is incorrect } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string token = req.Query["token"]; string Leave_ID = req.Query["LeaveID"]; GenerateResponses Gr = new GenerateResponses(); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); token = token ?? data?.name; Leave_ID = Leave_ID ?? data?.LeaveID; Console.WriteLine(Leave_ID); //update leavapplication set leave_status='A' where leave_id in ($values); DatabaseConnector DBConn = new DatabaseConnector(); SqlConnection connection = DBConn.connector("Users"); connection.Open(); SqlCommand UpdateLeaveStatus = new SqlCommand("update leaveapplication set leave_status='R' where leave_id=@Leave_ID", connection); UpdateLeaveStatus.Parameters.AddWithValue("@Leave_ID", Leave_ID); SqlCommand GetUserName = new SqlCommand("select username from Users where session_token=@token", connection); GetUserName.Parameters.AddWithValue("@token", token); UpdateLeaveStatus.ExecuteNonQuery(); SqlDataReader reader = GetUserName.ExecuteReader(); reader.Close(); Console.WriteLine("Days and Types Done"); reader = GetUserName.ExecuteReader(); string uname, email; uname = email = null; while (reader.Read()) { uname = reader[0].ToString(); } reader.Close(); _ = await SendEmail(email, uname); connection.Close(); return(Gr.OkResponse(Gr.OKRESP)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request.- Verification"); string VerifCode = req.Query["code"]; //Get Verification Code string email = req.Query["email"]; //Get Email string uname = req.Query["uname"]; string pswrd = req.Query["pswrd"]; string fname = req.Query["fname"]; string dptmt = req.Query["dptmt"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); VerifCode = VerifCode ?? data?.code; email = email ?? data?.email; uname = uname ?? data?.uname; pswrd = pswrd ?? data?.pswrd; fname = fname ?? data?.fname; dptmt = dptmt ?? data?.dptmt; string[] Data = { email, uname, pswrd, fname, dptmt }; GenerateHash GH = new GenerateHash(); //Object for Hash Generating class string Hash = GH.Generate(email + VerifCode); // Generate SHA256 hash from email and verification code string Hash_val = null; //Initialize Hash_val SqlDataReader rdr; //SQL Data Reader DatabaseConnector DBConn = new DatabaseConnector(); //Database Connection class object SqlConnection connection = DBConn.connector("Users"); //Connect to the Database GenerateResponses Gr = new GenerateResponses(); //Check if connection is null, if null return internal server error since database is not connected if (connection == null) { Gr.InternalServerError("Error connecting to database - Verification"); } // End if database cannot be connected //Open connection connection.Open(); //Console.WriteLine("Hash:" + Hash); //Generate SQL query SqlCommand cmd = new SqlCommand("select OTP_Hash from OTP where OTP_hash=@hash", connection); cmd.Parameters.AddWithValue("@hash", Hash); //Execute query and put data into rdr rdr = cmd.ExecuteReader(); //Read data, get the first data in the array since there's only one coloumn while (rdr.Read()) { Hash_val = rdr[0].ToString(); } rdr.Close(); //Console.WriteLine(Hash_val); //Debug //If Val is null or empty, it means that specific hash doesn't exist and OTP is invalid for that email if (string.IsNullOrEmpty(Hash_val)) { return(Gr.NotAcceptable("Invalid OTP"));// Ends if OTP is invalid } connection.Close(); PushUserData(Data, connection); connection.Open(); //Generate SQL query to delete OTP_Hash from the table cmd = new SqlCommand("delete from OTP where OTP_hash=@hash", connection); cmd.Parameters.AddWithValue("@hash", Hash); cmd.ExecuteNonQuery(); //Execute the command connection.Close(); //Return value return(Gr.OkResponse("Valid OTP")); }