示例#1
0
        public UsersModule(IUserService userService) : base("users")
        {
            Get("/", x =>
            {
                Debug.Log($"Getting current user");
                try
                {
                    this.RequiresAuthentication();

                    string currentUsername = this.Context.CurrentUser.Identity.Name;
                    UserModel userModel    = userService.Get(currentUsername);
                    SIM.InitUser(userModel.Username);
                    return(UserResponse.Create(userModel));
                }
                catch (RouteExecutionEarlyExitException ex)
                {
                    return(Response.AsJson(new { error = $"User is not authorized: {ex.Message}", cloudUrl = Config.CloudUrl }, Nancy.HttpStatusCode.Unauthorized));
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                    return(Response.AsJson(new { error = $"Failed to get user: {ex.Message}" }, Nancy.HttpStatusCode.InternalServerError));
                }
            });

            Put("/{token}", async x =>
            {
                Debug.Log($"Updating user with token");
                try
                {
                    var client = new HttpClient();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    var postData    = new [] { new KeyValuePair <string, string>("token", x.token) };
                    var formContent = new FormUrlEncodedContent(postData);

                    var response = await client.PutAsync(Config.CloudUrl + "/users/token", formContent);
                    var content  = await response.Content.ReadAsStringAsync();

                    var json            = JSONNode.Parse(content);
                    UserModel userModel = new UserModel()
                    {
                        Username  = json["username"].Value,
                        SecretKey = json["secretKey"].Value,
                        Settings  = json["settings"].Value
                    };
                    userService.AddOrUpdate(userModel);
                    SIM.InitUser(userModel.Username);

                    var guid = Guid.NewGuid();
                    UserMapper.RegisterUserSession(guid, userModel.Username);
                    return(this.LoginWithoutRedirect(guid, DateTime.UtcNow.AddSeconds(Config.sessionTimeout)));
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                    return(Response.AsJson(new { error = $"Failed to add/update user by token: {x.token}, {ex.Message}" }, Nancy.HttpStatusCode.InternalServerError));
                }
            });
        }
示例#2
0
        async void LoginAsync()
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");

                var postData = new[] { new KeyValuePair <string, string>("username", Config.Username),
                                       new KeyValuePair <string, string>("password", Config.Password),
                                       new KeyValuePair <string, string>("returnUrl", Config.WebHost + Config.WebPort) };
                var postForm     = new FormUrlEncodedContent(postData);
                var postResponse = await client.PostAsync(Config.CloudUrl + "/users/signin", postForm);

                var postContent = await postResponse.Content.ReadAsStringAsync();

                var postJson = JSONNode.Parse(postContent);

                var putData     = new[] { new KeyValuePair <string, string>("token", postJson["token"].Value) };
                var formContent = new FormUrlEncodedContent(putData);

                var response = await client.PutAsync(Config.CloudUrl + "/users/token", formContent);

                var content = await response.Content.ReadAsStringAsync();

                var       json      = JSONNode.Parse(content);
                UserModel userModel = new UserModel()
                {
                    Username  = json["username"].Value,
                    SecretKey = json["secretKey"].Value,
                    Settings  = json["settings"].Value
                };

                if (string.IsNullOrEmpty(userModel.Username))
                {
                    throw new Exception("Invalid Login: incorrect login info or account does not exist");
                }

                UserService userService = new UserService();
                userService.AddOrUpdate(userModel);
                SIM.InitUser(userModel.Username);

                var guid = Guid.NewGuid();
                UserMapper.RegisterUserSession(guid, userModel.Username);
                Config.SessionGUID = guid.ToString();

                Server.Start();
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
#if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
#else
                // return non-zero exit code
                Application.Quit(1);
#endif
                return;
            }
        }