コード例 #1
0
ファイル: Apply.cs プロジェクト: xzeck/LMS2019AzureBackend
        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"));
        }
コード例 #2
0
        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));
        }
コード例 #3
0
        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
            }
        }
コード例 #4
0
        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"));
        }