public CourseDE CreateCourse(CourseDto courseDto)
        {
            // validation
            if (string.IsNullOrWhiteSpace(courseDto.CourseCode))
            {
                throw new AppException("Course Code is required");
            }

            if (_context.tbl_course.Any(x => x.CourseCode == courseDto.CourseCode))
            {
                throw new AppException("Course Code \"" + courseDto.CourseCode + "\" is unavailable");
            }

            UserDE user = _userRepository.GetUsers(new List <Guid>(new Guid[] { courseDto.CreatedBy })).FirstOrDefault();

            if (user == null || string.Equals(user.Role, "student", StringComparison.OrdinalIgnoreCase))
            {
                throw new AppException("User \"" + courseDto.CreatedBy + "\" does not exist");
            }

            CourseDE course = new CourseDE();

            course           = _mapper.Map <CourseDto, CourseDE>(courseDto);
            course.CourseId  = new Guid();
            course.CreatedOn = DateTime.Now;

            _context.tbl_course.Add(course);
            _context.SaveChanges();

            return(course);
        }
示例#2
0
        public User Authenticate(User usermodel)
        {
            UserDE ude  = new UserDE();
            User   user = ude.UserTryLogin(usermodel);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.UserID.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);

            return(user.WithoutPassword());
        }
        public ContentDE AddContent(ContentDto contentDto)
        {
            ContentDE content = _mapper.Map <ContentDE>(contentDto);

            if (!_courseRepository.CourseExists(contentDto.CourseId))
            {
                throw new AppException("CourseId does not exist");
            }

            UserDE user = _userRepository.GetUser(contentDto.CreatedBy);

            if (user == null || !user.Role.Equals("lecturer", StringComparison.OrdinalIgnoreCase))
            {
                throw new AppException("Staff " + contentDto.CreatedBy + " does not exist");
            }

            if (!String.IsNullOrEmpty(contentDto.FileName) && String.IsNullOrEmpty(contentDto.Url))
            {
                throw new AppException("Url is empty for " + contentDto.FileName);
            }

            content.ContentId = new Guid();
            content.CreatedOn = DateTime.Now;

            _context.tbl_content.Add(content);
            _context.SaveChanges();

            return(content);
        }
示例#4
0
        public async Task <IActionResult> Register([FromBody] UserRegisterModel user)
        {
            UserDE userDE = new UserDE();
            await userDE.AddUser(user);

            return(Ok(new RegisterResultModel {
                Successful = true
            }));
        }
示例#5
0
        public IEnumerable <User> Get(int id)
        {
            // GET: api/User
            //HttpContext.RiseError(new InvalidOperationException("Test"));
            User   user   = new User();
            UserDE userDE = new UserDE();

            return(userDE.GetUser(id));
        }
        public void DeleteUser(Guid userId)
        {
            UserDE user = GetUser(userId);

            if (user == null)
            {
                throw new AppException("User not found");
            }

            _context.tbl_user.Remove(user);
        }
        public UserDE Create(UserCreationDto user)
        {
            // default password when admin creates a user
            if (string.IsNullOrWhiteSpace(user.Password))
            {
                user.Password = "******";
            }

            // validation
            if (_context.tbl_user.Any(x => x.UserName == user.UserName))
            {
                throw new AppException("Username \"" + user.UserName + "\" is already taken");
            }

            if (user.Email != null)
            {
                if (_context.tbl_user.Any(x => x.Email == user.Email))
                {
                    throw new AppException("Email \"" + user.Email + "\" is already taken");
                }
            }

            if (user.PhoneNo == null)
            {
                if (_context.tbl_user.Any(x => x.PhoneNo == user.PhoneNo))
                {
                    throw new AppException("Phone number \"" + user.PhoneNo + "\" is already taken");
                }
            }

            byte[] passwordHash, passwordSalt;
            CreatePasswordHash(user.Password, out passwordHash, out passwordSalt);

            UserDE newUser = new UserDE
            {
                UserId       = new Guid(),
                UserName     = user.UserName,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Email        = user.Email,
                PhoneNo      = user.PhoneNo,
                Role         = user.Role
            };

            _context.tbl_user.Add(newUser);
            _context.SaveChanges();

            return(newUser);
        }
示例#8
0
        public IActionResult Delete(int id)
        {
            // DELETE: api/ApiWithActions/5
            UserDE userDE = new UserDE();
            bool   sonuc  = userDE.DeleteUser(id);

            if (sonuc)
            {
                return(Ok());
            }
            else
            {
                return(NotFound());
            }
        }
        public void UpdateUser(Guid userId, UserDE userParam)
        {
            UserDE user = GetUser(userId);

            if (user == null)
            {
                throw new AppException("User not found");
            }

            // Update user properties
            user.UserName = string.IsNullOrEmpty(userParam.UserName) ? user.UserName : userParam.UserName;
            user.Email    = string.IsNullOrEmpty(userParam.Email) ? user.Email : userParam.Email;
            user.PhoneNo  = string.IsNullOrEmpty(userParam.PhoneNo) ? user.PhoneNo : userParam.PhoneNo;

            _context.tbl_user.Update(user);
        }
示例#10
0
        public IActionResult Put([FromBody] User user)
        {
            // POST: api/User
            // this post method insert the new row or update the current row if there is a record with same ID
            UserDE userDE = new UserDE();
            bool   sonuc  = userDE.UpdateUser(user, user.Candidate, user.Company);

            if (sonuc)
            {
                return(Ok());
            }
            else
            {
                return(NotFound());
            }
        }
        public void UpdatePassword(UserDE user, string password)
        {
            byte[] passwordHash, passwordSalt;

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new AppException("Password is required");
            }

            CreatePasswordHash(password, out passwordHash, out passwordSalt);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            _context.tbl_user.Update(user);

            if (!Save())
            {
                throw new AppException("Error in updating password.");
            }
        }
示例#12
0
        public async Task <IActionResult> Login([FromBody] AuthenticateModel login)
        {
            LoginResultModel umodel = new LoginResultModel(); // TO DO : user modelsiz yap ya da daha efficient
            UserDE           userDE = new UserDE();

            umodel = userDE.UserLogin(login);

            if (umodel == null)
            {
                return(BadRequest(new LoginResultModel {
                    Successful = false, Error = "Hatalı mail veya şifre."
                }));
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, login.Mail),
                new Claim(ClaimTypes.Role, umodel.Role.ToString()),
                new Claim(ClaimTypes.PrimarySid, umodel.UserID.ToString())//?? gerekli mi
            };

            var key    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSecurityKey"]));
            var creds  = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiry = DateTime.Now.AddDays(Convert.ToInt32(_configuration["JwtExpiryInDays"]));

            var token = new JwtSecurityToken(
                _configuration["JwtIssuer"],
                _configuration["JwtAudience"],
                claims,
                expires: expiry,
                signingCredentials: creds
                );

            //umodel.Successful = true;
            //umodel.Token = new JwtSecurityTokenHandler().WriteToken(token);

            return(Ok(new LoginResultModel {
                Successful = true, Token = new JwtSecurityTokenHandler().WriteToken(token)
            }));
        }
        public IEnumerable <CourseStaffDE> AddCourseStaff(List <CourseStaffDto> courseStaffDto)
        {
            IList <CourseStaffDE> courseStaff = new List <CourseStaffDE>();

            foreach (CourseStaffDto c in courseStaffDto)
            {
                UserDE user = _userRepository.GetUser(c.StaffId);
                if (user == null || !user.Role.Equals("lecturer", StringComparison.OrdinalIgnoreCase))
                {
                    throw new AppException("Staff " + c.StaffId + " does not exist");
                }

                if (!CourseExists(c.CourseId))
                {
                    throw new AppException("Course " + c.CourseId + " does not exist");
                }

                c.Id       = new Guid();
                c.IsActive = true;

                //Only update IsActive when staff has previously registred to the course
                CourseStaffDE existingStaff = _context.tbl_course_staff.Where(x => x.CourseId == c.CourseId && x.StaffId == c.StaffId).FirstOrDefault();
                if (existingStaff == null)
                {
                    courseStaff.Add(_mapper.Map <CourseStaffDE>(c));
                }
                else if (!existingStaff.IsActive)
                {
                    existingStaff.IsActive = true;
                    _context.tbl_course_staff.Update(existingStaff);
                }
            }

            _context.tbl_course_staff.AddRange(courseStaff);
            _context.SaveChanges();

            return(courseStaff);
        }
示例#14
0
 public async Task DeleteUser(int userID)
 {
     UserDE userDE = new UserDE();
     await userDE.DeleteUser(userID);
 }
示例#15
0
 public async Task UpdateUser([FromBody] UserModel user)
 {
     UserDE userDE = new UserDE();
     await userDE.EditUser(user);
 }
示例#16
0
        public async Task <IEnumerable <UserModel> > GetUsers(int userID = 0)
        {
            UserDE userDE = new UserDE();

            return(await userDE.GetUsers(userID));
        }