Esempio n. 1
0
        public IActionResult Get(int id)
        {
            string token = this.Request.Headers["Authorization"];

            if (token == null)
            {
                return(HttpBadRequest(new { error = "No authorization header" }));
            }

            bool isValid = JWTAuth.ValidateToken(token, id);

            if (!isValid)
            {
                this.Response.StatusCode = 403;
                return(new ObjectResult(new { error = "Invalid access token" }));
            }

            User user = _db.Users.FirstOrDefault(u => u.Id == id);

            return(new ObjectResult(new
            {
                user.Id,
                user.Username,
                user.Firstname,
                user.Middlename,
                user.Lastname,
                user.Age
            }));
        }
Esempio n. 2
0
        public IActionResult Login([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(HttpBadRequest(ModelState));
            }

            User _user = _db.Users.FirstOrDefault(
                u => u.Username == user.Username &&
                u.Password == user.Password);

            if (_user == null)
            {
                return(new HttpUnauthorizedResult());
            }

            string accessToken = JWTAuth.GenerateToken(_user);

            return(new ObjectResult(new
            {
                _user.Id,
                _user.Username,
                access_token = accessToken
            }));
        }
Esempio n. 3
0
        public IActionResult Get(string id)
        {
            string token = this.Request.Headers["Authorization"];

            if (token == null)
            {
                return(BadRequest(new { error = "No authorization header" }));
            }

            bool isValid = JWTAuth.ValidateToken(token, id);

            if (!isValid)
            {
                this.Response.StatusCode = 403;
                return(new ObjectResult(new { error = "Invalid access token" }));
            }


            User user = _usersService.GetForId(id);

            return(new ObjectResult(new
            {
                user.Id,
                user.Mail,
                user.Password,
            }));
        }
Esempio n. 4
0
        public IActionResult SendMail([FromBody] Temp temp)
        {
            OtherMetods oth = new OtherMetods();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (_usersService.GetForMailTemp(temp.Mail) != null)
            {
                return(BadRequest(new { error = "Mail already in use" }));
            }

            temp.Password = oth.RandomString();
            _usersService.SendMail(temp);
            oth.SendMail(temp);

            string accessToken = JWTAuth.GenerateToken(temp);

            return(new ObjectResult(new
            {
                temp.Mail,
                temp.Password,
                access_token = accessToken
            }));
        }
        protected async Task CreatePost(PostCreateModel post)
        {
            JWTAuth auth = new JWTAuth(_config["wpuri"]);

            auth.User = new JWTUser {
                UserName = _config["wpuser"],
                Password = _config["wppw"],
            };
            var httpResponseMsg = await auth.RequestJWToken();

            var content  = httpResponseMsg.Content.ReadAsStringAsync().Result;
            var response = JsonConvert.DeserializeObject <JWTResponse>(content);

            auth.Token = response.Token;
            if (await auth.IsValidJWToken())
            {
                var result = await auth.PostAsync(post);

                if (!result.IsSuccessStatusCode)
                {
                    throw new Exception(nameof(post));
                }
            }
            else
            {
                throw new Exception("invalid/expired token");
            }
        }
        public ActionResult <string> UploadImage([FromForm] Upload upload)
        {
            var username = JWTAuth.GetUsername(HttpContext.User);

            if (username is null)
            {
                return(BadRequest("Bearer token doesn't carry username"));
            }

            if (!unitOfWork.Users.Exists(username))
            {
                return(Unauthorized("User does not exist"));
            }

            //TODO: abstract writing file to disk
            var allowedExtensions = new List <string>()
            {
                ".gif", ".png", ".jpeg", ".jpg"
            };

            if (!allowedExtensions.Contains(Path.GetExtension(upload.File.FileName)))
            {
                return(BadRequest("File type not supported"));
            }

            var    imageId    = Guid.NewGuid().ToString();
            string uploadPath = Path.Combine(webHostEnvironment.WebRootPath, $"{username}/");

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            var fileName     = imageId + Path.GetExtension(upload.File.FileName);
            var diskFilePath = Path.Combine(uploadPath, fileName);
            var path         = $"/{username}/" + fileName;

            using var fileStream = new FileStream(diskFilePath, FileMode.Create);
            try
            {
                upload.File.CopyTo(fileStream);
                var image = new Image()
                {
                    Id        = imageId,
                    Username  = username,
                    Path      = path,
                    IsPrivate = upload.IsPrivate
                };
                unitOfWork.Images.Create(image);
                unitOfWork.Save();
                return(Ok(path));
            }
            catch (Exception e)
            {
                return(UnprocessableEntity(e));
            }
        }
Esempio n. 7
0
 // GET api/<controller>
 public IEnumerable <Persons> Get()
 {
     if (Request.Headers.Contains("Authorization"))
     {
         var token = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
         if (JWTAuth.ValidateJwtToken(token))
         {
             return(lstPersons);
         }
     }
     return(null);
 }
Esempio n. 8
0
 public HttpResponseMessage Get()
 {
     if (Request.Headers.Contains("Authorization"))
     {
         var token = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
         if (JWTAuth.ValidateJwtToken(token))
         {
             return(Request.CreateResponse(HttpStatusCode.OK, users));
         }
         return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid token"));
     }
     return(Request.CreateResponse(HttpStatusCode.Unauthorized, "No authorization header"));
 }
Esempio n. 9
0
        public ActionResult <string> Login([FromForm] User user)
        {
            if (String.IsNullOrEmpty(user.Username))
            {
                return(BadRequest("Username is null or empty"));
            }

            if (!unitOfWork.Users.Exists(user.Username))
            {
                return(NotFound("Username doesn't exist"));
            }

            return(JWTAuth.GenerateJWT(user.Username, configuration));
        }
Esempio n. 10
0
        private AuthenticateResponse Authenticate(AuthenticateRequest authenticateRequest)
        {
            var user = users.SingleOrDefault(x => x.Username == authenticateRequest.Username && x.Password == authenticateRequest.Password);

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

            // authentication successful so generate jwt token
            var token = JWTAuth.generateJwtToken(user);

            return(new AuthenticateResponse(user, token));
        }
Esempio n. 11
0
        public ActionResult <string> Signup([FromForm] User newUser)
        {
            if (String.IsNullOrEmpty(newUser.Username))
            {
                return(BadRequest("Username is null or empty"));
            }

            if (unitOfWork.Users.Exists(newUser.Username))
            {
                return(Conflict("Username already in use"));
            }

            unitOfWork.Users.Create(newUser);
            unitOfWork.Save();

            return(JWTAuth.GenerateJWT(newUser.Username, configuration));
        }
Esempio n. 12
0
 public HttpResponseMessage Get(int id)
 {
     if (Request.Headers.Contains("Authorization"))
     {
         var token = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
         if (JWTAuth.ValidateJwtToken(token))
         {
             var item = lstPersons.FirstOrDefault(x => x.id == id);
             if (item != null)
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, item));
             }
             return(Request.CreateResponse(HttpStatusCode.NotFound));
         }
         return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid token"));
     }
     return(Request.CreateResponse(HttpStatusCode.Unauthorized, "No authorization header"));
 }
        public ActionResult <List <Image> > GetImages(string username)
        {
            string currentUserName = JWTAuth.GetUsername(HttpContext.User);

            if (!unitOfWork.Users.Exists(username))
            {
                return(Unauthorized("User does not exist"));
            }

            IEnumerable images;

            if (currentUserName == username)
            {
                images = unitOfWork.Images.GetEntities(i => i.Username.Equals(username));
            }
            else
            {
                images = unitOfWork.Images.GetEntities(i => i.Username.Equals(username) && !i.IsPrivate);
            }

            return(Ok(images));
        }
Esempio n. 14
0
        public IActionResult Post([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (_usersService.GetForMail(user.Mail) != null)
            {
                return(BadRequest(new { error = "Mail already in use" }));
            }

            _usersService.Create(user);

            string accessToken = JWTAuth.GenerateToken(user);

            return(new ObjectResult(new
            {
                user.Id,
                user.Mail,
                access_token = accessToken
            }));
        }
Esempio n. 15
0
        public IActionResult Post([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(HttpBadRequest(ModelState));
            }

            var users = _db.Users;

            // Validate uniqueness of submitted username
            if (users.FirstOrDefault(u => u.Username == user.Username) != null)
            {
                return(HttpBadRequest(new { error = "Username already in use" }));
            }

            // Auto increment Id
            if (users.Count == 0)
            {
                user.Id = 1;
            }
            else
            {
                user.Id = users.Last().Id + 1;
            }

            _db.Users.Add(user);
            _db.SaveChanges();

            string accessToken = JWTAuth.GenerateToken(user);

            return(new ObjectResult(new
            {
                user.Id,
                user.Username,
                access_token = accessToken
            }));
        }
Esempio n. 16
0
        public IActionResult Login([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            User _user = _usersService.GetForMail(user.Mail);

            if (_user == null)
            {
                return(new UnauthorizedResult());
            }

            string accessToken = JWTAuth.GenerateToken(_user);

            return(new ObjectResult(new
            {
                _user.Id,
                _user.Mail,
                _user.Password,
                access_token = accessToken,
            }));
        }
Esempio n. 17
0
 public LoginController(IConfiguration configuration)
 {
     Configuration = configuration;
     jwt           = new JWTAuth(Configuration);
 }
Esempio n. 18
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.White;
            OAuthToken accessToken = null;

            try
            {
                accessToken = JWTAuth.AuthenticateWithJWT("ESignature", ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["ImpersonatedUserId"],
                                                          ConfigurationManager.AppSettings["AuthServer"], ConfigurationManager.AppSettings["PrivateKeyFile"]);
            }
            catch (ApiException apiExp)
            {
                // Consent for impersonation must be obtained to use JWT Grant
                if (apiExp.Message.Contains("consent_required"))
                {
                    // Caret needed for escaping & in windows URL
                    string caret = "";
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        caret = "^";
                    }

                    // build a URL to provide consent for this Integration Key and this userId
                    string url = "https://" + ConfigurationManager.AppSettings["AuthServer"] + "/oauth/auth?response_type=code" + caret + "&scope=impersonation%20signature" + caret +
                                 "&client_id=" + ConfigurationManager.AppSettings["ClientId"] + caret + "&redirect_uri=" + DevCenterPage;
                    Console.WriteLine($"Consent is required - launching browser (URL is {url})");

                    // Start new browser window for login and consent to this app by DocuSign user
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        Process.Start(new ProcessStartInfo("cmd", $"/c start {url}")
                        {
                            CreateNoWindow = false
                        });
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        Process.Start("xdg-open", url);
                    }
                    else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        Process.Start("open", url);
                    }

                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Unable to send envelope; Exiting. Please rerun the console app once consent was provided");
                    Console.ForegroundColor = ConsoleColor.White;
                    Environment.Exit(-1);
                }
            }

            var apiClient = new ApiClient();

            apiClient.SetOAuthBasePath(ConfigurationManager.AppSettings["AuthServer"]);
            UserInfo userInfo = apiClient.GetUserInfo(accessToken.access_token);
            Account  acct     = userInfo.Accounts.FirstOrDefault();

            Console.WriteLine("Welcome to the JWT Code example! ");
            Console.Write("Enter the signer's email address: ");
            string signerEmail = Console.ReadLine();

            Console.Write("Enter the signer's name: ");
            string signerName = Console.ReadLine();

            Console.Write("Enter the carbon copy's email address: ");
            string ccEmail = Console.ReadLine();

            Console.Write("Enter the carbon copy's name: ");
            string ccName  = Console.ReadLine();
            string docDocx = Path.Combine(@"..", "..", "..", "..", "launcher-csharp", "World_Wide_Corp_salary.docx");
            string docPdf  = Path.Combine(@"..", "..", "..", "..", "launcher-csharp", "World_Wide_Corp_lorem.pdf");

            Console.WriteLine("");
            string envelopeId = SigningViaEmail.SendEnvelopeViaEmail(signerEmail, signerName, ccEmail, ccName, accessToken.access_token, acct.BaseUri + "/restapi", acct.AccountId, docDocx, docPdf, "sent");

            Console.WriteLine("");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Successfully sent envelope with envelopeId {envelopeId}");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.ForegroundColor = ConsoleColor.White;
            Environment.Exit(0);
        }