Esempio n. 1
0
        public async Task <ActionResult <List <User> > > Get([FromHeader] string authToken)
        {
            string userId = AuthenticationHelpers.GetUserIdFromToken(authToken);

            User user = await _userService.Get(userId);

            if (user.ProPoints != null)
            {
                List <Dictionary <string, object> > eventsAttended = new List <Dictionary <string, object> >();

                foreach (PPUserEntry entry in user.ProPoints)
                {
                    Dictionary <string, object> userEntry = new Dictionary <string, object>();
                    PPEvent eventt = await _ppEventService.Get(entry.EventId);

                    userEntry["eventName"]   = eventt.Name;
                    userEntry["checkInUtc"]  = entry.CheckInUtc;
                    userEntry["checkOutUtc"] = entry.CheckOutUtc;
                    userEntry["points"]      = entry.Points;
                    eventsAttended.Add(userEntry);
                }
                return(Ok(eventsAttended));
            }

            return(NotFound());
        }
Esempio n. 2
0
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, SupplierUpdate supplierIn)
        {
            if (!await _authenticationService.CheckAccess(authToken, "orderMgr"))
            {
                return(Unauthorized());
            }

            var supplier = await _supplierService.Get(id);

            if (supplier == null)
            {
                return(NotFound());
            }

            _supplierService.Update(supplier, supplierIn);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "suppliers",
                                         id,
                                         JsonSerializer.Serialize(Supplier.FromUpdate(supplier, supplierIn))
                                         ));

            return(Ok());
        }
        public async Task ShouldUseDelegateAuthProviderWhenUserAccessTokenIsProvidedAsync()
        {
            // Arrange
            string accessToken = "ACCESS_TOKEN_VIA_DELEGATE_PROVIDER";

            GraphSession.Instance.UserProvidedToken = new NetworkCredential(string.Empty, accessToken).SecurePassword;
            AuthContext userProvidedAuthContext = new AuthContext
            {
                AuthType     = AuthenticationType.UserProvidedAccessToken,
                ContextScope = ContextScope.Process
            };

            IAuthenticationProvider authProvider   = AuthenticationHelpers.GetAuthProvider(userProvidedAuthContext);
            HttpRequestMessage      requestMessage = new HttpRequestMessage();

            // Act
            await authProvider.AuthenticateRequestAsync(requestMessage);

            // Assert
            Assert.IsType <DelegateAuthenticationProvider>(authProvider);
            Assert.Equal("Bearer", requestMessage.Headers.Authorization.Scheme);
            Assert.Equal(accessToken, requestMessage.Headers.Authorization.Parameter);

            // reset static instance.
            GraphSession.Reset();
        }
Esempio n. 4
0
        public async Task TestAddImagesToAlbum()
        {
            var imgurClient = await AuthenticationHelpers.CreateOAuth2AuthenticatedImgurClient();

            var albumEndpoint = new AlbumEndpoint(imgurClient);
            var imageEndpoint = new ImageEndpoint(imgurClient);

            var filePath     = VariousFunctions.GetTestsAssetDirectory() + @"\upload-image-example.jpg";
            var imageBinary  = File.ReadAllBytes(filePath);
            var createdAlbum = await albumEndpoint.CreateAlbumAsync();

            await
            albumEndpoint.AddImageToAlbumAsync(createdAlbum.Data.Id,
                                               (await imageEndpoint.UploadImageFromBinaryAsync(imageBinary)).Data.Id);

            var updatedAlbum = await albumEndpoint.GetAlbumDetailsAsync(createdAlbum.Data.Id);

            // Assert the Reponse
            Assert.IsNotNull(updatedAlbum.Data);
            Assert.AreEqual(updatedAlbum.Success, true);
            Assert.AreEqual(updatedAlbum.Status, HttpStatusCode.OK);

            // Assert the data
            Assert.AreEqual(createdAlbum.Data.ImagesCount + 1, updatedAlbum.Data.ImagesCount);
        }
Esempio n. 5
0
        public async Task <ActionResult <User> > Create(UserCreate user)
        {
            string pass = user.Password;

            user.Password = AuthenticationHelpers.EncrpytPassword(user.Password);

            User created = await _userService.Create(user);

            if (!_hostEnvironment.EnvironmentName.Equals("Development", StringComparison.OrdinalIgnoreCase))
            {
                EmailHelpers.SendRegistrationConfirmationEmail(created.TechMail, created.Username, pass);
            }

            await _logService.Create(new Log(
                                         null,
                                         created.Id,
                                         DateTime.UtcNow,
                                         "Document created.",
                                         "auth.users",
                                         created.Id,
                                         JsonSerializer.Serialize(created)
                                         ));

            return(Ok(user));
        }
        public async Task <IActionResult> UpdateCalibrations([FromHeader] string authToken, string stockId, CalibrationCreate cal)
        {
            if (!await _authenticationService.CheckAccess(authToken, "equipmentMgr"))
            {
                return(Unauthorized());
            }

            StockItem item = await _stockItemService.Get(stockId);

            if (item == null)
            {
                return(NotFound());
            }

            Equipment eq = await _equipmentService.GetFromStockId(stockId);

            Calibration calibration = Calibration.FromCreate(AuthenticationHelpers.GetUserIdFromToken(authToken), cal);

            _stockItemService.AddCalibration(eq.Id, item, calibration);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "StockItem modified.",
                                         "equipment",
                                         eq.Id,
                                         JsonSerializer.Serialize(_stockItemService.Get(stockId))
                                         ));

            return(Ok());
        }
        public async Task <IActionResult> DeleteCalibration([FromHeader] string authToken, string stockId, string time)
        {
            if (!await _authenticationService.CheckAccess(authToken, "equipmentMgr"))
            {
                return(Unauthorized());
            }

            StockItem item = await _stockItemService.Get(stockId);


            if (item == null)
            {
                return(NotFound());
            }

            DateTime calibrationDate = DateTime.Parse(time).ToUniversalTime();

            Equipment eq = await _equipmentService.GetFromStockId(stockId);

            _stockItemService.RemoveCalibration(eq.Id, item, calibrationDate);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "StockItem modified.",
                                         "equipment",
                                         eq.Id,
                                         JsonSerializer.Serialize(_stockItemService.Get(stockId))
                                         ));

            return(Ok());
        }
        public async Task <IActionResult> Delete([FromHeader] string authToken, string stockId)
        {
            if (!await _authenticationService.CheckAccess(authToken, "equipmentMgr"))
            {
                return(Unauthorized());
            }

            StockItem item = await _stockItemService.Get(stockId);

            if (item == null)
            {
                return(NotFound());
            }

            Equipment eq = await _equipmentService.GetFromStockId(stockId);

            await _stockItemService.Delete(stockId);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "StockItem deleted.",
                                         "equipment",
                                         eq.Id,
                                         JsonSerializer.Serialize(item)
                                         ));

            return(Ok());
        }
Esempio n. 9
0
        public void CanGetFingerprint()
        {
            string fingerprint = AuthenticationHelpers.GetFingerprint();

            Assert.That(fingerprint, Is.Not.Null);
            Assert.That(fingerprint, Is.Not.Empty);
        }
Esempio n. 10
0
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, LabGroupUpdate update)
        {
            if (!await _authenticationService.CheckAccess(authToken, "groupMgr"))
            {
                return(Unauthorized());
            }

            LabGroup group = await _labGroupService.Get(id);

            if (group == null)
            {
                return(NotFound());
            }

            _labGroupService.Update(group, update);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "labGroups",
                                         id,
                                         JsonSerializer.Serialize(LabGroup.FromUpdate(group, update))
                                         ));

            return(Ok());
        }
Esempio n. 11
0
        public async Task TestCreateAlbum()
        {
            var imgurClient = await AuthenticationHelpers.CreateOAuth2AuthenticatedImgurClient();

            var albumEndpoint = new AlbumEndpoint(imgurClient);
            var imageEndpoint = new ImageEndpoint(imgurClient);

            var filePath    = VariousFunctions.GetTestsAssetDirectory() + @"\upload-image-example.jpg";
            var imageBinary = File.ReadAllBytes(filePath);

            var title       = String.Format("dicks-{0}", new Random().Next(100, 1337));
            var description = String.Format("black dicks, yo-{0}", new Random().Next(100, 1337));

            var uploadedImages = new List <Image>();

            for (var i = 0; i < 2; i++)
            {
                uploadedImages.Add((await imageEndpoint.UploadImageFromBinaryAsync(imageBinary)).Data);
            }
            var createdAlbum = await albumEndpoint.CreateAlbumAsync(uploadedImages.ToArray(), uploadedImages[0], title, description);

            // Assert the Reponse
            Assert.IsNotNull(createdAlbum.Data);
            Assert.AreEqual(createdAlbum.Success, true);
            Assert.AreEqual(createdAlbum.Status, HttpStatusCode.OK);

            // Assert the data
            Assert.AreEqual(createdAlbum.Data.Title, title);
            Assert.AreEqual(createdAlbum.Data.Description, description);
        }
Esempio n. 12
0
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, PPEventUpdate update)
        {
            if (!await _authenticationService.CheckAccess(authToken, "ppEventMgr"))
            {
                return(Unauthorized());
            }

            var ppEvent = await _ppEventService.Get(id);

            if (ppEvent == null)
            {
                return(NotFound());
            }

            _ppEventService.Update(ppEvent, update);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "pp.events",
                                         id,
                                         JsonSerializer.Serialize(PPEvent.FromUpdate(ppEvent, update))
                                         ));

            return(Ok());
        }
Esempio n. 13
0
        public async Task TestGetBadAccount()
        {
            var imgurClient     = AuthenticationHelpers.CreateClientAuthenticatedImgurClient();
            var accountEndpoint = new AccountEndpoint(imgurClient);
            ImgurResponse <Account> imgurResponse = null;

            try
            {
                imgurResponse = await accountEndpoint.GetAccountDetailsAsync("black-dicks (this account doesn't exist, perfect for le test)");
            }
            catch (ImgurResponseFailedException exception)
            {
                // Assert the Response
                Assert.IsNotNull(exception.ImgurResponse.Data);
                Assert.AreEqual(exception.ImgurResponse.Success, false);
                Assert.AreEqual(exception.ImgurResponse.Status, HttpStatusCode.BadRequest);

                // Assert the Data
                Assert.AreEqual(exception.ImgurResponse.Data.ErrorDescription, "A username is required.");
                Assert.AreEqual(exception.ImgurResponse.Data.Method, "GET");
                Assert.AreEqual(exception.ImgurResponse.Data.Request, "/3/account/black-dicks (this account doesn't exist, perfect for le test)");
            }

            Assert.IsNull(imgurResponse);
        }
        protected async Task <object> ProcessMessageRequestAsync(HttpRequest request, GoogleAdapter GoogleAdapter, BotCallbackHandler botCallbackHandler)
        {
            GoogleRequestBody actionRequest;
            Payload           actionPayload;

            var memoryStream = new MemoryStream();

            request.Body.CopyTo(memoryStream);
            memoryStream.Position = 0;

            var projectId = AuthenticationHelpers.GetProjectIdFromRequest(request);

            GoogleAdapter.ActionProjectId = projectId;

            using (var bodyReader = new StreamReader(memoryStream, Encoding.UTF8))
            {
                var skillRequestContent = bodyReader.ReadToEnd();
                try
                {
                    actionRequest = JsonConvert.DeserializeObject <GoogleRequestBody>(skillRequestContent);
                    actionPayload = actionRequest.OriginalDetectIntentRequest.Payload;
                }
                catch
                {
                    actionPayload = JsonConvert.DeserializeObject <Payload>(skillRequestContent);
                }
            }

            var responseBody = await GoogleAdapter.ProcessActivity(
                actionPayload,
                botCallbackHandler);

            return(responseBody);
        }
Esempio n. 15
0
        public async Task <IActionResult> Delete([FromHeader] string authToken, string id)
        {
            if (!await _authenticationService.CheckAccess(authToken, "ppEventMgr"))
            {
                return(Unauthorized());
            }

            var ppEvent = await _ppEventService.Get(id);

            if (ppEvent == null)
            {
                return(NotFound());
            }

            await _ppEventService.Delete(id);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document deleted.",
                                         "pp.events",
                                         id,
                                         null
                                         ));

            return(Ok());
        }
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, RoleUpdate roleIn)
        {
            if (!await _authenticationService.CheckAccess(authToken, "roleMgr"))
            {
                return(Unauthorized());
            }

            var role = await _roleService.Get(id);

            if (role == null)
            {
                return(NotFound());
            }

            _roleService.Update(id, roleIn);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "auth.roles",
                                         id,
                                         JsonSerializer.Serialize(Role.FromUpdate(id, roleIn))
                                         ));

            return(Ok());
        }
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, ToolGroupUpdate groupIn)
        {
            if (!await _authenticationService.CheckAccess(authToken, "stuToolMgr"))
            {
                return(Unauthorized());
            }

            var toolGroup = await _toolService.Get(id);

            if (toolGroup == null)
            {
                return(NotFound());
            }

            _toolService.Update(toolGroup, groupIn);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "toolGroups",
                                         id,
                                         JsonSerializer.Serialize(ToolGroup.FromUpdate(toolGroup, groupIn))
                                         ));

            return(Ok());
        }
Esempio n. 18
0
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, UserUpdate userIn)
        {
            if (!await _authenticationService.CheckAccess(authToken, "userMgr"))
            {
                return(Unauthorized());
            }

            var user = await _userService.Get(id);

            if (user == null)
            {
                return(NotFound());
            }

            if (!user.Password.Equals(userIn.Password))
            {
                // TODO: Check to verify this works on the stockroom server
                if (!_hostEnvironment.EnvironmentName.Equals("Development", StringComparison.OrdinalIgnoreCase))
                {
                    EmailHelpers.SendPasswordResetEmail(userIn.TechMail, userIn.Password);
                }
                userIn.Password = AuthenticationHelpers.EncrpytPassword(userIn.Password);

                // Kill all active sessions
                await _tokenService.InvalidateUserTokens(user.Id);
            }

            var permDiff = user.Permissions.Except(userIn.Permissions);
            var roleDiff = user.Roles.Except(userIn.Roles);
            var certDiff = user.Certs.Except(userIn.Certs);

            if (permDiff.Count() != 0 || roleDiff.Count() != 0 || certDiff.Count() != 0)
            {
                // Kill all active sessions
                await _tokenService.InvalidateUserTokens(user.Id);
            }

            if (user.CountryCode != null)
            {
                if (!user.CountryCode.Equals(userIn.CountryCode) || !user.PhoneNumber.Equals(userIn.PhoneNumber))
                {
                    userIn.PhoneVerifiedFlag     = false;
                    userIn.PhoneVerificationCode = await SMSHelpers.SendVerificationCode(userIn.CountryCode, userIn.PhoneNumber);
                }
            }

            _userService.Update(user, userIn);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "auth.users",
                                         id,
                                         JsonSerializer.Serialize(ecestockroom_api.Models.Authentication.User.FromUpdate(user, userIn))
                                         ));

            return(Ok());
        }
Esempio n. 19
0
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, LabBenchUpdate benchIn)
        {
            if (!await _authenticationService.CheckAccess(authToken, "benchMgr"))
            {
                return(Unauthorized());
            }

            LabBench bench = await _labBenchService.Get(id);

            if (bench == null)
            {
                return(NotFound());
            }

            _labBenchService.Update(bench, benchIn);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "labBenches",
                                         id,
                                         JsonSerializer.Serialize(LabBench.FromUpdate(bench, benchIn))
                                         ));

            return(Ok());
        }
Esempio n. 20
0
        public void CanResolveNetworkInterface()
        {
            var net = AuthenticationHelpers.GetNetworkInterface();

            Assert.That(net, Is.Not.Null);
            Assert.That(net, Is.Not.Empty);
        }
        public void ShouldUseCertThumbPrintInsteadOfPassedInCertificateWhenBothAreSpecified()
        {
            // Arrange
            var         dummyCertName          = "CN=dummycert";
            var         inMemoryCertName       = "CN=inmemorycert";
            var         storedDummyCertificate = CreateAndStoreSelfSignedCert(dummyCertName);
            var         inMemoryCertificate    = CreateSelfSignedCert(inMemoryCertName);
            AuthContext appOnlyAuthContext     = new AuthContext
            {
                AuthType = AuthenticationType.AppOnly,
                ClientId = Guid.NewGuid().ToString(),
                CertificateThumbprint = storedDummyCertificate.Thumbprint,
                Certificate           = inMemoryCertificate,
                ContextScope          = ContextScope.Process
            };
            // Act
            IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(appOnlyAuthContext);

            // Assert
            Assert.IsType <ClientCredentialProvider>(authProvider);
            var clientCredentialProvider = (ClientCredentialProvider)authProvider;

            // Assert: That the certificate used is dummycert (Thumbprint), that is in the store
            Assert.NotEqual(inMemoryCertName, clientCredentialProvider.ClientApplication.AppConfig.ClientCredentialCertificate.SubjectName.Name);
            Assert.Equal(appOnlyAuthContext.CertificateThumbprint, clientCredentialProvider.ClientApplication.AppConfig.ClientCredentialCertificate.Thumbprint);

            //CleanUp
            DeleteSelfSignedCertByThumbprint(appOnlyAuthContext.CertificateThumbprint);
            GraphSession.Reset();
        }
Esempio n. 22
0
        public void CanGetMachineName()
        {
            string name = AuthenticationHelpers.GetMachineName();

            Assert.That(name, Is.Not.Null);
            Assert.That(name, Is.Not.Empty);
        }
Esempio n. 23
0
        public async Task <ActionResult <Order> > Create([FromHeader] string authToken, bool stockroom, OrderCreate create)
        {
            if (stockroom)
            {
                if (!await _authenticationService.CheckAccess(authToken, "orderMgr"))
                {
                    return(Unauthorized());
                }

                Order created = await _orderService.CreateStockroom(create);

                await _logService.Create(new Log(
                                             null,
                                             AuthenticationHelpers.GetUserIdFromToken(authToken),
                                             DateTime.UtcNow,
                                             "Order Placed",
                                             "orders",
                                             created.Id,
                                             JsonSerializer.Serialize(created)
                                             ));

                return(Ok(created));
            }
            else
            {
                if (!await _authenticationService.CheckAccess(authToken, "orderView"))
                {
                    return(Unauthorized());
                }

                LabGroup group = await _labGroupService.GetByMemberId(AuthenticationHelpers.GetUserIdFromToken(authToken));

                Order created = await _orderService.Create(create, group.Id);

                group.BudgetBalance = group.BudgetBalance - (created.UnitCost * created.Quantity);

                group.Transactions.Add(new Transaction(
                                           created.Id,
                                           "Remove",
                                           "Order Submitted",
                                           (created.UnitCost * created.Quantity),
                                           DateTime.UtcNow
                                           ));

                _labGroupService.Update(group, group.Id);

                await _logService.Create(new Log(
                                             null,
                                             AuthenticationHelpers.GetUserIdFromToken(authToken),
                                             DateTime.UtcNow,
                                             "Order Placed",
                                             "orders",
                                             created.Id,
                                             JsonSerializer.Serialize(created)
                                             ));

                return(Ok(created));
            }
        }
        public async Task <IActionResult> CheckQuiz([FromHeader] string authToken, List <Dictionary <string, string> > completedQuiz)
        {
            if (!await _authenticationService.CheckAccess(authToken, "certView"))
            {
                return(Unauthorized());
            }

            User user = await _userService.Get(AuthenticationHelpers.GetUserIdFromToken(authToken));

            if (user == null)
            {
                return(NotFound());
            }

            int numCorrect = 0;

            foreach (Dictionary <string, string> answer in completedQuiz)
            {
                QuizQuestion question = await _quizQuestionService.Get(answer["id"]);

                if (question.CorrectAnswer == answer["answerChoice"])
                {
                    numCorrect++;
                }
            }

            if (numCorrect < 7)
            {
                return(BadRequest("You scored under a 70%, please try again"));
            }
            else
            {
                if (user.Certs == null)
                {
                    user.Certs = new List <string>();
                }

                user.Certs.Add("61e49344c9828fb8c104f09b");

                user.Roles.Add("611fcd612cec2947ae2693b0");

                user.Permissions.Add("612036892cec2947ae2693e6");
                user.Permissions.Add("6120464d2cec2947ae2693fe");
                user.Permissions.Add("6120464d2cec2947ae269400");
                user.Permissions.Add("612048372cec2947ae269402");
                user.Permissions.Add("61268b352cec2947ae26942d");
                user.Permissions.Add("6126f55b2cec2947ae269453");
                user.Permissions.Add("6138d1f15e5ae5a54af905e3");
                user.Permissions.Add("614de8e274ad73e6ce9f07ae");
                user.Permissions.Add("61db5d523fb8d66a6bbdde39");
                user.Permissions.Add("61db606a3fb8d66a6bbdde43");

                _userService.Update(user.Id, user);

                await _tokenService.InvalidateUserTokens(user.Id);

                return(Ok("Great Work! You Passed with a " + (numCorrect * 10) + "%!"));
            }
        }
        public async Task <ActionResult <List <Dictionary <string, object> > > > Get([FromHeader] string authToken, [FromQuery] string view)
        {
            if (!await _authenticationService.CheckAccess(authToken, "logView"))
            {
                return(Unauthorized());
            }

            List <Dictionary <string, object> > logs = new List <Dictionary <string, object> >();

            if (view == "orders")
            {
                LabGroup group = await _labGroupService.GetByMemberId(AuthenticationHelpers.GetUserIdFromToken(authToken));

                logs = await _logViewService.GetOrderHistory(view, group, _supplierService);
            }

            else if (view == "transactions")
            {
                LabGroup group = await _labGroupService.GetByMemberId(AuthenticationHelpers.GetUserIdFromToken(authToken));

                int i = 1;
                foreach (Transaction t in group.Transactions)
                {
                    Dictionary <string, object> transaction = new Dictionary <string, object>();
                    transaction["action"]      = t.Action;
                    transaction["amount"]      = t.Amount;
                    transaction["description"] = t.Description;
                    if (t.OrderId == string.Empty || t.OrderId == null)
                    {
                        transaction["order"] = null;
                    }
                    else
                    {
                        Order o = await _orderService.Get(t.OrderId);

                        Supplier s = await _supplierService.Get(o.SupplierId);

                        Dictionary <string, object> order = new Dictionary <string, object>();
                        order["placedUtc"]  = o.PlacedUtc;
                        order["partNumber"] = o.PartNumber;
                        if (!(s == null))
                        {
                            order["supplierName"] = s.Name;
                        }
                        order["url"]         = o.Url;
                        transaction["order"] = order;
                    }
                    transaction["utc"] = t.Utc;
                    transaction["key"] = i;
                    logs.Add(transaction);
                    i++;
                }
            }


            return(logs);
        }
Esempio n. 26
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    TempData.AddErrorMessage(WebConstants.ErrorTryAgain);
                    return(RedirectToHome());
                }

                Picture profilePicture = new Picture();

                Stream stream             = new MemoryStream(model.ProfilePictureBytes);
                Image  pictureImage       = Image.FromStream(stream);
                bool   imageInsertSuccess = await pictureService.InsertAsync(profilePicture, pictureImage); // inserts image into database and file system

                if (!imageInsertSuccess)                                                                    // if something with the image goes wrong return error
                {
                    TempData.AddErrorMessage(WebConstants.ErrorTryAgain);
                    return(View(nameof(ExternalLogin), model));
                }

                string[] personalNames = AuthenticationHelpers.GetNamesFromExternalLogin(model.Username); // Extracts the first and last name of the person
                User     user          = new User
                {
                    UserName               = AuthenticationHelpers.GenerateUniqueUsername(personalNames[0], personalNames[1]),
                    Email                  = model.Email,
                    FirstName              = personalNames[0],
                    LastName               = personalNames[1],
                    PhoneNumber            = model.PhoneNumber,
                    ProfilePictureFileName = profilePicture.FileName
                };

                IdentityResult result = await userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        await signInManager.SignInAsync(user, isPersistent : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }

                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }
Esempio n. 27
0
        public async Task <ActionResult <LabGroup> > Create([FromHeader] string authToken, LabGroupCreate create)
        {
            if (!await _authenticationService.CheckAccess(authToken, "groupMgr"))
            {
                return(Unauthorized());
            }

            List <string> members = new List <string>();

            foreach (string techId in create.Members)
            {
                User temp = await _userService.GetByTechId(techId);

                members.Add(temp.Id);
            }

            LabCourse course = await _labCourseService.Get(create.LabCourseId);

            LabGroupCreate editCreate = create;

            editCreate.Members       = members;
            editCreate.Budget        = course.InitialBudget;
            editCreate.BudgetBalance = course.InitialBudget;
            editCreate.GroupNumber   = (course.LabGroups == null) ?  1 : course.LabGroups.Count + 1;
            editCreate.Transactions  = new List <Transaction>();
            editCreate.Transactions.Add(new Transaction(null, "Add", "Initial Budget", course.InitialBudget, DateTime.UtcNow));

            LabGroup created = await _labGroupService.Create(editCreate);

            await _labCourseService.AddGroup(course, created.Id);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Group created.",
                                         "labGroups",
                                         created.Id,
                                         JsonSerializer.Serialize(created)
                                         ));

            foreach (string id in created.Members)
            {
                User temp = await _userService.Get(id);

                temp.Permissions.Add("61db5dde3fb8d66a6bbdde3b");
                temp.Permissions.Add("61db59a03fb8d66a6bbdde34");
                temp.Permissions.Add("61db5a813fb8d66a6bbdde36");

                await _tokenService.InvalidateUserTokens(temp.Id);

                _userService.Update(temp.Id, temp);
            }

            return(Ok(created));
        }
Esempio n. 28
0
        public async Task <IActionResult> Register(UserFormViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                TempData.AddErrorMessage(WebConstants.AlreadyRegistered);
                return(RedirectToHome());
            }

            if (!ModelState.IsValid || model.ImageFile == null)
            {
                TempData.AddErrorMessage(WebConstants.ErrorTryAgain);
                return(View(model));
            }

            Picture profilePicture      = new Picture();                                                  // Creates instance of Picture entity
            Image   profilePictureImage = PictureServiceHelpers.ConvertIFormFileToImage(model.ImageFile); // Converts the uploaded image to System.Drawing.Image

            if (profilePictureImage == null)                                                              // The uploaded file is not a picture
            {
                TempData.AddErrorMessage(WebConstants.ErrorTryAgain);
                return(View(model));
            }

            bool imageInsertSuccess = await pictureService.InsertAsync(profilePicture, profilePictureImage); // inserts image into database and file system

            if (!imageInsertSuccess)                                                                         // if something with the image goes wrong return error
            {
                TempData.AddErrorMessage(WebConstants.ErrorTryAgain);
                return(View(model));
            }

            User user = new User
            {
                UserName               = AuthenticationHelpers.GenerateUniqueUsername(model.FirstName, model.LastName),
                Email                  = model.Email,
                FirstName              = model.FirstName,
                LastName               = model.LastName,
                PhoneNumber            = model.PhoneNumber,
                ProfilePictureFileName = profilePicture.FileName
            };

            IdentityResult result = await userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)                                // If something with the insert of a user goes wrong return an error
            {
                await pictureService.DeleteAsync(profilePicture); // In that case delete the already inserted profile picture

                AddErrors(result);
                return(View(model));
            }

            await signInManager.SignInAsync(user, false); // Signs the new user

            TempData.AddSuccessMessage(WebConstants.SuccessfulRegistration);
            return(RedirectToHome());
        }
Esempio n. 29
0
        public void CanCreateSha256Hash()
        {
            const string hello = "Hello World";
            var          hash  = AuthenticationHelpers.Sha256Hash(hello);

            Assert.That(hash, Is.Not.Null);
            Assert.That(hash, Is.Not.Empty);
            Assert.That(hash, Is.Not.EqualTo(hello));
            Assert.That(hash, Is.EqualTo("a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e"));
        }
        public async Task <ActionResult> SwipeOut([FromHeader] string authToken, string techId, string eventId)
        {
            if (!await _authenticationService.CheckAccess(authToken, "ppSwipe"))
            {
                return(Unauthorized());
            }

            User user = await _userService.GetByTechId(techId);

            PPEvent ppEvent = await _ppEventService.Get(eventId);

            if (user == null)
            {
                return(NotFound("tech id not found"));
            }

            if (ppEvent == null)
            {
                return(NotFound("pro point event not found"));
            }

            PPUserEntry userEvent = user.ProPoints.Find(entry => entry.EventId == eventId);

            if (userEvent == null)
            {
                return(Problem("user never checked in"));
            }

            if (userEvent.CheckOutUtc != null)
            {
                return(Problem("user already checked out"));
            }

            DateTime now     = DateTime.UtcNow;
            TimeSpan elapsed = now - userEvent.CheckInUtc;
            int      hours   = (int)Math.Round(elapsed.TotalHours);
            int      points  = (hours * ppEvent.HourlyPointRate) + ppEvent.BasePointRate;

            userEvent.CheckOutUtc = now;
            userEvent.Points      = points;

            _userService.Update(user.Id, user);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "User checked out for Pro Point Event.",
                                         "auth.users",
                                         user.Id,
                                         JsonSerializer.Serialize(user)
                                         ));

            return(Ok());
        }