Esempio n. 1
0
        public void GenerateAndVerifyPasswordTest()
        {
            var(hashed, salt) = HashPasswordGenerator.GeneratePasswordHash("kainkain", 1);
            Assert.True(HashPasswordGenerator.VerifyPassword("kainkain", 1, hashed, salt));
            (hashed, salt) = HashPasswordGenerator.GeneratePasswordHash("gjpostrjhriosjgbiodj", 1333);
            Assert.True(HashPasswordGenerator.VerifyPassword("gjpostrjhriosjgbiodj", 1333, hashed, salt));
            Assert.False(HashPasswordGenerator.VerifyPassword("VerifyPassword", 1333, hashed, salt));
            (hashed, salt) = HashPasswordGenerator.GeneratePasswordHash("kain", 1);

            _output.WriteLine("hash:" + hashed);
            _output.WriteLine("salt:" + salt);
        }
Esempio n. 2
0
        public async Task <ActionResult <UserResponse> > Add([FromBody] UserRequest request)
        {
            if (request == null)
            {
                return(BadRequest(new { errorText = "No request data." }));
            }

            if (_context.Users.Any(u => u.Login == request.Login))
            {
                return(BadRequest(new { errorText = "User with that login already exists." }));
            }

            if (!_context.UserStatus.Any(us => us.UserStatusId == request.UserStatusId))
            {
                return(BadRequest(new { errorText = "Wrong UserStatusId." }));
            }

            int userRole = _context.Roles.First(r => string.Equals(r.Name, "User", StringComparison.CurrentCultureIgnoreCase)).RoleId;

            User newUser = new User()
            {
                Login        = request.Login,
                Password     = HashPasswordGenerator.GenerateHash(request.Password),
                CoreId       = Guid.NewGuid(),
                UserStatusId = request.UserStatusId
            };

            _context.Users.Add(newUser);

            _context.SaveChanges();

            UserRole newUserRole = new UserRole()
            {
                UserId = newUser.UserId,
                RoleId = userRole
            };

            _context.UserRoles.Add(newUserRole);


            await _context.SaveChangesAsync();

            Response.StatusCode = 201;
            return(new UserResponse()
            {
                Login = newUser.Login,
                Password = newUser.Password,
                UserStatusId = newUser.UserStatusId,
                CoreId = newUser.CoreId
            });
        }
Esempio n. 3
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Setting default data into variable
            const int    adminRoleId    = 1;
            const int    activeStatusId = 1;
            const long   adminUserId    = 1;
            const int    userRoleId     = 1;
            const string adminLogin     = "******";
            const string adminPassword  = "******";

            // Sets default user roles in VDCore.Roles table
            Role adminRole = new Role()
            {
                RoleId = adminRoleId, Name = "Administrator"
            };
            Role userRole = new Role()
            {
                RoleId = adminRoleId + 1, Name = "User"
            };

            modelBuilder.Entity <Role>().HasData(adminRole, userRole);

            // Sets default user roles in VDCore.UserStatus table
            UserStatus activeStatus = new UserStatus()
            {
                UserStatusId = activeStatusId, StatusName = "Active"
            };
            UserStatus disabledStatus = new UserStatus()
            {
                UserStatusId = activeStatusId + 1, StatusName = "Disabled"
            };

            modelBuilder.Entity <UserStatus>().HasData(activeStatus, disabledStatus);

            // Adds default admin user
            User adminUser = new User()
            {
                UserId       = adminUserId,
                Login        = adminLogin,
                Password     = HashPasswordGenerator.GenerateHash(adminPassword),
                CoreId       = Guid.NewGuid(),
                UserStatusId = activeStatus.UserStatusId
            };

            modelBuilder.Entity <User>().HasData(adminUser);
            modelBuilder.Entity <UserRole>().HasData(new UserRole()
            {
                Id = userRoleId, RoleId = adminRole.RoleId, UserId = adminUser.UserId
            });
        }
Esempio n. 4
0
        public async Task <ActionResult <UserResponse> > Update([FromBody] UserUpdateRequest request)
        {
            if (request == null)
            {
                return(BadRequest(new { errorText = "No request data." }));
            }

            if (!_context.Users.Any(x => x.CoreId == Guid.Parse(request.CoreId)))
            {
                return(NotFound(new { errorText = "User with coreId " + request.CoreId + " is not found." }));
            }

            User userForUpdate = _context.Users.First(u => u.CoreId == Guid.Parse(request.CoreId));

            if (_context.Users.Any(u => u.Login == request.Login))
            {
                return(BadRequest(new { errorText = "User with that login already exists." }));
            }

            if (!_context.UserStatus.Any(us => us.UserStatusId == request.UserStatusId))
            {
                return(BadRequest(new { errorText = "Wrong UserStatusId." }));
            }

            // Updating user data.
            userForUpdate.Login        = request.Login;
            userForUpdate.Password     = HashPasswordGenerator.GenerateHash(request.Password);
            userForUpdate.UserStatusId = request.UserStatusId;
            _context.Update(userForUpdate);

            await _context.SaveChangesAsync();

            return(Ok(new UserResponse()
            {
                Login = userForUpdate.Login,
                Password = userForUpdate.Password,
                UserStatusId = userForUpdate.UserStatusId,
                CoreId = userForUpdate.CoreId
            }));
        }
Esempio n. 5
0
        public IActionResult Login(LoginRequest request)
        {
            var student = new Student();

            using var con = new SqlConnection(ConnectionString);
            using (var com = new SqlCommand())
            {
                com.Connection = con;
                var salt     = String.Empty;
                var password = String.Empty;
                com.CommandText = "Select IndexNumber, FirstName Password, Salt From Student Where IndexNumber = @login";
                com.Parameters.AddWithValue("login", request.Login);
                con.Open();
                var dr = com.ExecuteReader();

                if (!dr.Read())
                {
                    return(NotFound("Student was not found."));
                }

                student.IndexNumber = dr["IndexNumber"].ToString();
                student.FirstName   = dr["FirstName"].ToString();
                password            = dr["Password"].ToString();
                salt = dr["Salt"].ToString();

                var passToCompare = HashPasswordGenerator.HashPasswordGen(request.Password, salt);

                if (!password.Equals(passToCompare))
                {
                    return(BadRequest("Wrong login or password"));
                }

                dr.Close();

                var userclaim = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, student.IndexNumber),
                    new Claim(ClaimTypes.Name, student.FirstName),
                    new Claim(ClaimTypes.Role, "Student"),
                };

                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecretKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: "Gakko",
                    audience: "Students",
                    claims: userclaim,
                    expires: DateTime.Now.AddMinutes(1),
                    signingCredentials: creds
                    );

                student.RefreshToken = Guid.NewGuid().ToString();
                student.RefreshTokenExpirationDate = DateTime.Now.AddDays(1);

                com.CommandText = "Update Student set RefreshToken = @RefreshToken and RefreshTokenExpirationDate = @ExpDate";
                com.Parameters.AddWithValue("RefreshToken", student.RefreshToken);
                com.Parameters.AddWithValue("ExpDate", student.RefreshTokenExpirationDate);

                return(Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    refreshToken = student.RefreshToken
                }));
            }
        }
Esempio n. 6
0
        public EnrollStudentResponse EnrollStudent(EnrollStudentRequest request)
        {
            var response = new EnrollStudentResponse();

            using (var con = new SqlConnection(ConnectionString))
            {
                using (var com = new SqlCommand())
                {
                    com.Connection  = con;
                    com.CommandText = "Select * From Studies Where Name = @Name";
                    com.Parameters.AddWithValue("Name", request.Studies);
                    con.Open();

                    var trans = con.BeginTransaction();
                    com.Transaction = trans;
                    var dr = com.ExecuteReader();

                    if (!dr.Read())
                    {
                        dr.Close();
                        trans.Rollback();
                        return(null);
                    }

                    int idStudy = (int)dr["IdStudy"];

                    dr.Close();

                    com.CommandText = "Select * From Enrollment Where Semester = 1 And IdStudy = @idStudy";
                    int IdEnrollment = (int)dr["IdEnrollemnt"] + 1;
                    com.Parameters.AddWithValue("IdStudy", idStudy);
                    dr = com.ExecuteReader();

                    if (dr.Read())
                    {
                        dr.Close();
                        com.CommandText = "Select MAX(idEnrollment) as 'idEnrollment' From Enrollment";
                        dr = com.ExecuteReader();
                        dr.Close();
                        DateTime StartDate = DateTime.Now;
                        com.CommandText = "Insert Into Enrollment(IdEnrollment, Semester, IdStudy, StartDate, Password) Values (@IdEnrollemnt, 1, @IdStudy, @StartDate, @Password)";
                        com.Parameters.AddWithValue("IdEnrollemnt", IdEnrollment);
                        com.Parameters.AddWithValue("StartDate", StartDate);
                        com.ExecuteNonQuery();
                    }

                    dr.Close();

                    com.CommandText = "Select * From Student Where IndexNumber=@IndexNumber";
                    com.Parameters.AddWithValue("IndexNumber", request.IndexNumber);
                    dr = com.ExecuteReader();

                    if (!dr.Read())
                    {
                        var salt = SaltGenerator.SaltGen();
                        dr.Close();
                        com.CommandText = "Insert Into Student(IndexNumber, FirstName, LastName, Birthdate, IdEnrollment, Password, Salt) Value (@IndexNumber, @FirstName, @LastName, @BirthDate, @IdEnrollment, @Password, @Salt)";
                        com.Parameters.AddWithValue("FirstName", request.FirstName);
                        com.Parameters.AddWithValue("LastName", request.LastName);
                        com.Parameters.AddWithValue("BirthDate", request.BirthDate);
                        com.Parameters.AddWithValue("IdEnrollment", IdEnrollment);
                        com.Parameters.AddWithValue("Password", HashPasswordGenerator.HashPasswordGen(request.Password, salt));
                        com.Parameters.AddWithValue("Salt", salt);

                        com.ExecuteNonQuery();
                        dr.Close();

                        response.Semester = 1;
                    }
                    else
                    {
                        dr.Close();
                        trans.Rollback();
                        throw new Exception("Student with such index number already exists");
                    }

                    trans.Commit();
                }
            }

            return(response);
        }