public byte[] GetDecryptedAssignment(Guid submissionId)
        {
            SubmissionViewModel submission = _assignmentsService.GetSubmission(submissionId);

            FileStream fs = new FileStream(submission.FilePath, FileMode.Open, FileAccess.Read);

            MemberViewModel teacher = _membersService.GetMember(submission.Member.TeacherEmail);

            byte[] key = CryptographicHelper.AsymmetricDecrypt(
                Convert.FromBase64String(submission.SymmetricKey), teacher.PrivateKey);

            byte[] iv = CryptographicHelper.AsymmetricDecrypt(
                Convert.FromBase64String(submission.SymmetricIV), teacher.PrivateKey);


            MemoryStream ms = new MemoryStream();

            fs.CopyTo(ms);

            byte[] encryptedAssignment = ms.ToArray();

            byte[] decryptedAssignment = CryptographicHelper.SymmetricDecrypt(
                encryptedAssignment,
                key, iv);

            return(decryptedAssignment);
        }
        public IActionResult ViewSubmission(string id)
        {
            Guid decryptedId = Guid.Parse(
                HttpUtility.UrlDecode(
                    CryptographicHelper.SymmetricDecrypt(id)));

            ViewSubmissionViewModel submission = new ViewSubmissionViewModel();

            submission.Submission = _assignmentsService.GetSubmission(decryptedId);

            if (User.IsInRole("Teacher"))
            {
                var checks = CheckForAuthandInt(decryptedId);

                if (checks.Item2 == false)
                {
                    ViewData["isAuthentic"] = 0;
                }
            }

            var comments = _assignmentsService.GetComments(decryptedId);

            ViewBag.Comments = comments;
            return(View(submission));
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            AssignmentsController controller = (AssignmentsController)context.Controller;
            ILogger logger = controller.GetLogger();

            try
            {
                var id           = Guid.Parse(CryptographicHelper.SymmetricDecrypt(context.ActionArguments["id"].ToString()));
                var loggedInUser = context.HttpContext.User.Identity.Name;

                IAssignmentsService assignmentsService = (IAssignmentsService)context.HttpContext.RequestServices.GetService(typeof(IAssignmentsService));


                if (loggedInUser != assignmentsService.GetSubmission(id).Member.Email&& !context.HttpContext.User.IsInRole("Teacher"))
                {
                    IPHostEntry iphostinfo = Dns.GetHostEntry(Dns.GetHostName());

                    string ipaddress = Convert.ToString(iphostinfo.AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));

                    logger.LogInformation(loggedInUser + " on IP " + ipaddress + " tried to access submission with id " + id + ". Access was denied");

                    context.Result = new UnauthorizedObjectResult("Access Denied");
                }
            }
            catch (Exception ex)
            {
                logger.LogInformation("Bad request when user tried to access a file");
                context.Result = new BadRequestObjectResult("Bad Request");
            }

            base.OnActionExecuting(context);
        }
Esempio n. 4
0
        /// <summary>
        /// Mets à jour un utilisateur avec un nouveau mot de passe.
        /// </summary>
        /// <param name="id">L'id de l'utilisateur à mettre à jour.</param>
        /// <param name="clearPassword">Le mot de passe en clair, avant encryption.</param>
        /// <returns>Le résultat de la mise à jour.</returns>
        public ReplaceOneResult UpdatePassword(Guid id, string clearPassword)
        {
            User user = this.Get(id);

            string hashedPassword = CryptographicHelper.GetHash(clearPassword, this.appSettings.Security.HashSalt);

            user.Password = hashedPassword;

            return(this.Update(user));
        }
        public IActionResult ViewSubmissions(string assigmmentId)
        {
            Guid decryptedAssignmentId = Guid.Parse(
                HttpUtility.UrlDecode(
                    CryptographicHelper.SymmetricDecrypt(assigmmentId)));

            var list = _assignmentsService.GetSubmissions(decryptedAssignmentId);

            return(View(list));
        }
Esempio n. 6
0
        /// <summary>
        /// Crée un <see cref="UserPasswordResetToken"/>, avec gestion du hashage en base.
        /// </summary>
        /// <param name="elm">Le <see cref="UserPasswordResetToken"/> à créer.</param>
        /// <returns>L'élément créé.</returns>
        public override UserPasswordResetToken Create(UserPasswordResetToken elm)
        {
            // We are using a hash function for storing reset password token for security reasons.
            // Basically it makes it more difficult for an attacker with a read access to the database to gain access to the user account.
            // See https://security.stackexchange.com/questions/86913/should-password-reset-tokens-be-hashed-when-stored-in-a-database for more info.
            string hash = CryptographicHelper.GetHash(elm?.Token);

            elm.Token = hash;

            return(base.Create(elm));
        }
Esempio n. 7
0
        /// <summary>
        /// Crée un <see cref="User"/>.
        /// </summary>
        /// <param name="elm">Les données de le <see cref="User"/> a créé.</param>
        /// <returns>L'utilisateur créé.</returns>
        public override User Create(User elm)
        {
            if (elm == null)
            {
                throw new ArgumentNullException(nameof(elm));
            }

            string hashedPassword = CryptographicHelper.GetHash(elm.Password, this.appSettings.Security.HashSalt);

            elm.Password = hashedPassword;

            return(base.Create(elm));
        }
Esempio n. 8
0
 protected void OnGridViewRowUpdating(object sender, GridViewUpdateEventArgs e)
 {
     if (String.IsNullOrEmpty((string)e.NewValues["Password"]))
     {
         e.NewValues["Password"] = e.OldValues["Password"];
     }
     else
     {
         TRAVEL_WEBDataContext context = new TRAVEL_WEBDataContext();
         var salt = (from tk in context.TAI_KHOANs where tk.MaTaiKhoan == int.Parse(e.Keys["MaTaiKhoan"].ToString()) select tk.Salt).Single();
         e.NewValues["Password"] = CryptographicHelper.CreatePasswordHash((string)e.NewValues["Password"], salt);
     }
 }
Esempio n. 9
0
 protected void OnDetailsViewItemInserting(object sender, DetailsViewInsertEventArgs e)
 {
     if (String.IsNullOrEmpty((string)e.Values["Password"]))
     {
         e.Cancel = true;
     }
     else
     {
         e.Values["Salt"]         = CryptographicHelper.CreateSalt();
         e.Values["Password"]     = CryptographicHelper.CreatePasswordHash((string)e.Values["Password"], (string)e.Values["Salt"]);
         e.Values["NgayKichHoat"] = DateTime.Now;
     }
 }
Esempio n. 10
0
 public void ChangeUserPassword(string id, string password)
 {
     if (string.IsNullOrEmpty(id))
     {
         throw new ArgumentNullException(ExMessage.MustNotBeNullOrEmpty(nameof(id)));
     }
     if (string.IsNullOrEmpty(password))
     {
         throw new ArgumentNullException(ExMessage.MustNotBeNullOrEmpty(nameof(password)));
     }
     password = CryptographicHelper.Hash(password);
     _repository.ModifyPassword(id, password);
 }
Esempio n. 11
0
        /// <summary>
        /// Obtient un <see cref="UserPasswordResetToken"/>, basé sur la valeur du token.
        /// Notez que le token est hashé avant d'être comparé en base.
        /// </summary>
        /// <param name="token">La valeur du token à rechercher.</param>
        /// <returns>Le <see cref="UserPasswordResetToken"/>, si trouvé.</returns>
        public UserPasswordResetToken GetByToken(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

            // We are using a hash function for storing reset password token for security reasons.
            // Basically it makes it more difficult for an attacker with a read access to the database to gain access to the user account.
            // See https://security.stackexchange.com/questions/86913/should-password-reset-tokens-be-hashed-when-stored-in-a-database for more info.
            string hash = CryptographicHelper.GetHash(token);

            return(this.Entities.Find(elm => elm.Token == hash).FirstOrDefault());
        }
        public IActionResult SubmitAssignment(string id)
        {
            Guid decryptedId = Guid.Parse(
                HttpUtility.UrlDecode(CryptographicHelper.SymmetricDecrypt(id)));

            CookieOptions cookieOptions = new CookieOptions();

            Response.Cookies.Append("Assignment", id, cookieOptions);
            var assignment = _assignmentsService.GetAssignment(decryptedId);

            ViewBag.Assignment = assignment;

            return(View());
        }
Esempio n. 13
0
 public AccountController(
     UsersViewService usersService,
     CryptographicHelper cryptoHelper,
     IdGenerator idGenerator,
     AuthenticationService authenticationService,
     FacebookClientFactory fbFactory,
     SiteSettings settings)
 {
     _usersService          = usersService;
     _cryptoHelper          = cryptoHelper;
     _idGenerator           = idGenerator;
     _authenticationService = authenticationService;
     _fb       = fbFactory.GetClient();
     _settings = settings;
 }
        public IActionResult Delete(string id)
        {
            try
            {
                Guid decryptedId = Guid.Parse(
                    HttpUtility.UrlDecode(CryptographicHelper.SymmetricDecrypt(id)));
                _assignmentsService.DeleteAssignment(decryptedId);
                ViewData["info"] = "Assignment deleted";
            }catch (Exception ex)
            {
                ViewData["warning"] = "Error deleting assignment";
            }


            return(RedirectToAction("Index"));
        }
Esempio n. 15
0
 protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
 {
     if (!(e.NewValues["Salt"].Equals(e.OldValues["Salt"])))
     {
         e.Cancel = true;
     }
     else
     {
         if (String.IsNullOrEmpty((string)e.NewValues["Password"]))
         {
             e.NewValues["Password"] = e.OldValues["Password"];
         }
         else
         {
             e.NewValues["Password"] = CryptographicHelper.CreatePasswordHash((string)e.NewValues["Password"], (string)e.OldValues["Salt"]);
         }
     }
 }
Esempio n. 16
0
    // store the Oauth access token in OauthAccessTokenStorage.xml file
    public static void StoreOauthAccessToken(Page page)
    {
        string      path = page.Server.MapPath("/") + @"OauthAccessTokenStorage.xml";
        XmlDocument doc  = new XmlDocument();

        doc.Load(path);
        XmlNode      node = doc.CreateElement("record");
        XmlAttribute userMailIdAttribute = doc.CreateAttribute("usermailid");



        //userMailIdAttribute.Value = page.Session["FriendlyEmail"].ToString();
        userMailIdAttribute.Value = "*****@*****.**";



        node.Attributes.Append(userMailIdAttribute);

        XmlAttribute accessKeyAttribute = doc.CreateAttribute("encryptedaccesskey");
        string       secuirtyKey        = ConfigurationManager.AppSettings["securityKey"];

        accessKeyAttribute.Value = CryptographicHelper.EncryptData(page.Session["accessToken"].ToString(), secuirtyKey);
        node.Attributes.Append(accessKeyAttribute);

        XmlAttribute encryptedaccesskeysecretAttribute = doc.CreateAttribute("encryptedaccesskeysecret");

        encryptedaccesskeysecretAttribute.Value = CryptographicHelper.EncryptData(page.Session["accessTokenSecret"].ToString(), secuirtyKey);
        node.Attributes.Append(encryptedaccesskeysecretAttribute);

        XmlAttribute realmIdAttribute = doc.CreateAttribute("realmid");

        realmIdAttribute.Value = page.Session["realm"].ToString();
        node.Attributes.Append(realmIdAttribute);

        XmlAttribute dataSourceAttribute = doc.CreateAttribute("dataSource");

        dataSourceAttribute.Value = page.Session["dataSource"].ToString();
        node.Attributes.Append(dataSourceAttribute);

        doc.DocumentElement.AppendChild(node);
        doc.Save(path);
    }
Esempio n. 17
0
        /// <summary>
        /// Authentifie un <see cref="User"/>, basé sur le <see cref="UserAuthenticateModel"/> fourni.
        /// </summary>
        /// <param name="model">Le <see cref="UserAuthenticateModel"/> à utiliser pour authentifier l'<see cref="Utilisateur"/>.</param>
        /// <returns>L'<see cref="User">Utilisateur</see> authentifié.</returns>
        public User Authenticate(UserAuthenticateModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            string hashedPassword = CryptographicHelper.GetHash(model.Password, this.appSettings.Security.HashSalt);
            User   user           = this.Entities.Find(x => x.Username == model.Username && x.Password == hashedPassword).FirstOrDefault();

            if (user == null)
            {
                return(null);
            }
            else
            {
                if (user.Active == false)
                {
                    // Account is not active.
                    return(null);
                }

                // Generation du token JWT.
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(this.appSettings.Security.JWT.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Id.ToString()),
                        new Claim(ClaimTypes.Email, user.Email.ToString(CultureInfo.InvariantCulture)),
                    }),
                    Expires            = DateTime.UtcNow.AddDays(this.appSettings.Security.JWT.DurationInDays),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                };
                SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
                user.Token = tokenHandler.WriteToken(token);

                return(user.WithoutPassword());
            }
        }
Esempio n. 18
0
    // get the oauth access token for the user from OauthAccessTokenStorage.xml
    public static void GetOauthAccessTokenForUser(string emailID, Page page)
    {
        string      path            = page.Server.MapPath("/") + @"OauthAccessTokenStorage.xml";
        string      searchUserXpath = "//record[@usermailid='" + emailID + "']";
        XmlDocument doc             = new XmlDocument();

        doc.Load(path);
        XmlNode record = doc.SelectSingleNode(searchUserXpath);

        if (record != null)
        {
            page.Session["realm"]      = record.Attributes["realmid"].Value;
            page.Session["dataSource"] = record.Attributes["dataSource"].Value;
            string secuirtyKey = ConfigurationManager.AppSettings["securityKey"];
            page.Session["accessToken"]       = CryptographicHelper.DecryptData(record.Attributes["encryptedaccesskey"].Value, secuirtyKey);
            page.Session["accessTokenSecret"] = CryptographicHelper.DecryptData(record.Attributes["encryptedaccesskeysecret"].Value, secuirtyKey);

            // Add flag to session which tells that accessToken is in session
            page.Session["Flag"] = true;
        }
    }
        public IActionResult ViewFile(string id)
        {
            Guid decryptedId = Guid.Parse(HttpUtility.UrlDecode(CryptographicHelper.SymmetricDecrypt(id)));

            byte[] decryptedAssignment = GetDecryptedAssignment(decryptedId);

            IPHostEntry iphostinfo = Dns.GetHostEntry(Dns.GetHostName());

            string ipaddress = Convert.ToString(iphostinfo.AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));


            if (User.IsInRole("Teacher"))
            {
                _logger.LogInformation("Teacher " + User.Identity.Name + " on IP " + ipaddress + " accessed file of submission " + decryptedId + " on " + DateTime.Now);
            }
            else if (User.IsInRole("Student"))
            {
                _logger.LogInformation("Student " + User.Identity.Name + " on IP " + ipaddress + " accessed file of submission " + decryptedId + " on " + DateTime.Now);
            }

            return(File(decryptedAssignment, "application/pdf"));
        }
Esempio n. 20
0
        public static Picture Create(
            string appPath,
            string originalPath,
            string name,
            string folderName,
            string folderAppPath,
            int folderSortOrder,
            int size,
            int globalSortOrder,
            DateTime?created = null
            )
        {
            if (string.IsNullOrWhiteSpace(appPath))
            {
                throw new ArgumentNullException($"Parameter {nameof(appPath)} cannot be empty");
            }

            string id = CryptographicHelper.HashValues(appPath);

            if (string.IsNullOrWhiteSpace(folderAppPath))
            {
                folderAppPath = appPath.Replace(name, "").Replace("\\", "").Replace("/", "");
            }

            string folderId = CryptographicHelper.HashValues(folderAppPath);

            return(new Picture(id)
            {
                _name = name,
                _appPath = appPath,
                _originalPath = originalPath,
                _folderName = folderName,
                _folderId = folderId,
                _folderSortOrder = folderSortOrder,
                _size = size,
                _createTimestamp = created ?? DateTime.UtcNow,
                _globalSortOrder = globalSortOrder
            });
        }
        public Tuple <bool, bool> CheckForAuthandInt(Guid id)
        {
            bool isDistinct = true;
            bool isVerified = true;

            SubmissionViewModel submission = _assignmentsService.GetSubmission(id);

            var submissions = _assignmentsService.GetSubmissions(submission.Assignment.Id);

            MemberViewModel teacher = _membersService.GetMember(submission.Member.TeacherEmail);


            byte[] key = CryptographicHelper.AsymmetricDecrypt(
                Convert.FromBase64String(submission.SymmetricKey), teacher.PrivateKey);

            byte[] iv = CryptographicHelper.AsymmetricDecrypt(
                Convert.FromBase64String(submission.SymmetricIV), teacher.PrivateKey);

            foreach (SubmissionViewModel sub in submissions)
            {
                if (sub.FileHash == submission.FileHash && sub.Member.Email != submission.Member.Email)
                {
                    TempData["warning"] += "Assignment is identical to " + sub.Member.Email + "'s assignment!\n";
                    isDistinct           = false;
                }
            }

            if (!CryptographicHelper.VerifySignature(
                    CryptographicHelper.SymmetricDecrypt(
                        Convert.FromBase64String(submission.Signature), key, iv),
                    CryptographicHelper.Hash(GetDecryptedAssignment(id)),
                    submission.Member.PublicKey))
            {
                isVerified = false;
            }

            return(new Tuple <bool, bool>(isDistinct, isVerified));
        }
Esempio n. 22
0
        public string AddUser(OrgUser dto)
        {
            var user = _repository.FindByAccount(dto.Account);

            if (user != null)
            {
                throw new NonUniqueException($"user account must be unique,account={dto.Account}");
            }
            user = _repository.FindByCode(dto.Code);
            if (user != null)
            {
                throw new NonUniqueException($"user code must be unique,code={dto.Code}");
            }
            dto.Id       = ConfigHelper.NewGuid;
            dto.Password = CryptographicHelper.Hash(ConfigHelper.DefaultUserPwd);
            dto.State    = (int)UserState.Normal;
            if (string.IsNullOrEmpty(dto.Code))
            {
                dto.Code = dto.Id;
            }
            _repository.Add(dto);
            return(dto.Id);
        }
Esempio n. 23
0
        /// <summary>
        /// Enregistre un nouvel <see cref="User"/>.
        /// </summary>
        /// <param name="model">L'<see cref="User"/> a créé.</param>
        /// <returns>L'utilisateur créé.</returns>
        public User Register(User model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            // Le nom d'utilisateur doit être unique.
            if (this.GetByUsername(model.Username) != null)
            {
                throw new ArgumentException((this as ILocalizedService <UserService>).GetLocalized("RegisterErrorUserUsernameAlreadyExists", model.Username));
            }

            // L'email doit être unique.
            else if (this.GetByEmail(model.Email) != null)
            {
                throw new ArgumentException((this as ILocalizedService <UserService>).GetLocalized("RegisterErrorUserEmailAlreadyExists", model.Email));
            }

            model.ActivationToken = CryptographicHelper.GetUrlSafeToken(24);
            model.Active          = false;

            return(this.Create(model)?.WithoutPassword());
        }
Esempio n. 24
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    await _userManager.AddToRoleAsync(user, "Teacher");

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);


                        Tuple <string, string> keys = CryptographicHelper.GenerateAsymmetricKeys();


                        _membersService.AddMember(new SecuringApplicationsAssignment.Application.ViewModels.MemberViewModel
                        {
                            Email     = Input.Email,
                            FirstName = Input.FirstName,
                            LastName  = Input.LastName,
                            //Generating Keys for teacher
                            PrivateKey = keys.Item2,
                            PublicKey  = keys.Item1
                        }
                                                  );

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ProviderDisplayName = info.ProviderDisplayName;
            ReturnUrl           = returnUrl;
            return(Page());
        }
Esempio n. 25
0
        public IActionResult AddStudent(AddStudentModel model)
        {
            if (!ModelState.IsValid)
            {
                TempData["warning"] = "Invalid";
                return(View());
            }

            if (_membersService.GetMember(model.MemberModel.Email) != null)
            {
                TempData["warning"] = "Student already exists";
                return(RedirectToAction("Index", "Assignments"));
            }

            string randomPassword = GenerateRandomPassword();


            var user = new ApplicationUser {
                UserName = model.MemberModel.Email, Email = model.MemberModel.Email
            };

            var result = _userManager.CreateAsync(user, randomPassword);



            if (result.Result.Succeeded)
            {
                _userManager.AddToRoleAsync(user, "Student");

                EmailModel em = new EmailModel();
                em.Email         = "*****@*****.**";
                em.To            = model.MemberModel.Email;
                model.EmailModel = em;

                using (MailMessage mm = new MailMessage(model.EmailModel.Email, model.EmailModel.To))
                {
                    mm.Subject = "Login Credentials";
                    mm.Body    = "You have been assigned an account. Username is: " + em.To + " and your password is : " + randomPassword;

                    mm.IsBodyHtml = false;

                    using (SmtpClient smtp = new SmtpClient())
                    {
                        smtp.Host      = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        NetworkCredential NetworkCred = new NetworkCredential(model.EmailModel.Email, "74bf*XBG^0ga");
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials           = NetworkCred;
                        smtp.Port = 587;
                        smtp.Send(mm);
                        ViewBag.Message = "Email sent";
                    }
                }


                model.MemberModel.TeacherEmail = User.Identity.Name;

                Tuple <string, string> keys = CryptographicHelper.GenerateAsymmetricKeys();

                model.MemberModel.PublicKey  = keys.Item1;
                model.MemberModel.PrivateKey = keys.Item2;
                _membersService.AddMember(model.MemberModel);
            }

            return(RedirectToAction("Index", "Assignments"));
        }
 public AuthenticationService(UsersViewService users, CryptographicHelper crypto)
 {
     _users  = users;
     _crypto = crypto;
     _crypto = crypto;
 }
        public IActionResult SubmitAssignment(IFormFile file)
        {
            var assignment = _assignmentsService.GetAssignment(Guid.Parse(CryptographicHelper.SymmetricDecrypt(Request.Cookies["Assignment"])));

            ViewBag.Assignment = assignment;


            if (file != null)
            {
                Stream stream     = file.OpenReadStream();
                int    firstByte  = stream.ReadByte();
                int    secondByte = stream.ReadByte();
                int    thirdByte  = stream.ReadByte();
                int    fourthByte = stream.ReadByte();
                stream.Position = 0;


                //If the file passes the following check, a submission is created with user credentials
                if (firstByte == 37 && secondByte == 80 && thirdByte == 68 && fourthByte == 70 && Path.GetExtension(file.FileName) == ".pdf")
                {
                    SubmissionViewModel submission = new SubmissionViewModel();
                    submission.Member = _membersService.GetMember(User.Identity.Name);

                    Tuple <byte[], byte[]> keys = CryptographicHelper.GenerateKeys();


                    MemberViewModel teacher = _membersService.GetMember(submission.Member.TeacherEmail);

                    string encryptedKey = Convert.ToBase64String(CryptographicHelper.AsymmetricEncrypt(keys.Item1, teacher.PublicKey));

                    string encryptedIv = Convert.ToBase64String(CryptographicHelper.AsymmetricEncrypt(keys.Item2, teacher.PublicKey));


                    submission.SymmetricKey = encryptedKey;
                    submission.SymmetricIV  = encryptedIv;

                    submission.Assignment = _assignmentsService.GetAssignment(assignment.Id);


                    string absolutePath = _host.WebRootPath + @"\..\ProtectedFiles\";
                    string uniqueName   = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        stream.CopyTo(ms);
                        ms.Position = 0;

                        submission.FileHash = Convert.ToBase64String(CryptographicHelper.Hash(ms.ToArray()));

                        var signature = CryptographicHelper.GenerateSignature(Convert.FromBase64String(submission.FileHash), submission.Member.PrivateKey);

                        submission.Signature = Convert.ToBase64String(CryptographicHelper.SymmetricEncrypt(
                                                                          signature,
                                                                          keys.Item1, keys.Item2));


                        System.IO.File.WriteAllBytes(absolutePath + uniqueName,
                                                     CryptographicHelper.SymmetricEncrypt(
                                                         ms.ToArray(),
                                                         keys.Item1,
                                                         keys.Item2
                                                         )
                                                     );
                    }

                    submission.FilePath = absolutePath + uniqueName;
                    _assignmentsService.AddSubmission(submission);

                    TempData["info"] = "File accepted";

                    return(RedirectToAction("index"));
                }
                else
                {
                    TempData["warning"] = "File is not valid, only PDF allowed";
                    return(View());
                }
            }
            else
            {
                TempData["warning"] = "Please upload a file";

                return(View());
            }
        }
Esempio n. 28
0
 public UsersViewService(MongoViewDatabase database, CryptographicHelper crypto)
     : base(database)
 {
     _crypto = crypto;
 }
 public UserApplicationService(IRepository <UserAggregate> repository, CryptographicHelper crypto)
 {
     _repository = repository;
     _crypto     = crypto;
 }
        public IActionResult ForgotPassword([FromBody] UserPasswordLostModel model)
        {
            this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenTry"].Value));

            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            User user = null;

            if (!string.IsNullOrEmpty(model.Email))
            {
                user = this.userService.GetByEmail(model.Email);
            }
            else if (!string.IsNullOrEmpty(model.Username))
            {
                user = this.userService.GetByUsername(model.Username);
            }

            if (user == null)
            {
                this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenUserNotFound"].Value, new { method = !string.IsNullOrEmpty(model.Email) ? "email" : "username", value = model.Email ?? model.Username }));
                return(this.NotFound(new { message = string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenUserNotFound"].Value) }));
            }

            UserPasswordResetToken userPasswordResetToken;
            string token;

            try
            {
                token = CryptographicHelper.GetUrlSafeToken(24);
                userPasswordResetToken = new UserPasswordResetToken()
                {
                    Token      = token,
                    ValidUntil = DateTime.UtcNow.AddMinutes(this.appSettings.Security.ResetPasswordTokenDurationInMinutes),
                    Created    = DateTime.UtcNow,
                    CreatedBy  = new UserReference()
                    {
                        Id = user.Id, Username = user.Username
                    },
                };
                userPasswordResetToken = this.userPasswordResetTokenService.Create(userPasswordResetToken);

                // Sending reset password email, with token in clear value.
                this.emailService.SendTemplate(new EmailAddress()
                {
                    Address = user.Email, Name = user.Username
                }, "PasswordLost", new
                {
                    username          = user.Username,
                    resetpasswordlink = $"{new Uri(this.appSettings.Environment.FrontUrl, $"#/user/resetpassword/{token}")}",
                    sitename          = this.appSettings.Environment.Name,
                    siteurl           = this.appSettings.Environment.FrontUrl.ToString(),
                    unsubscribeurl    = new Uri(this.appSettings.Environment.FrontUrl, "/user/unsubscribe").ToString(),
                });
            }
            catch (Exception ex)
            {
                // TODO: Gérer les exceptions, avec message localisé
                this.logger.LogError(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenFailed"].Value));
                return(this.Problem(
                           statusCode: (int)HttpStatusCode.InternalServerError,
                           title: ex.ToString(),
                           detail: ex.StackTrace));
            }

            this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenSuccess"].Value, new { value = model.Email ?? model.Username }));
            return(this.Ok());
        }