document.write("
namespace AndroidApi.Models.Repository { public class TokenRepository : ITokenRepository { private static string connectionString = string.Empty; private static string tokenKey = string.Empty; private readonly IAccountRepository _repository; public TokenRepository() { _repository = new AccountRepository(); if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["appctxt"])) connectionString = ConfigurationManager.AppSettings["appctxt"]; if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["tokenPrivateKey"])) tokenKey = ConfigurationManager.AppSettings["tokenPrivateKey"]; } public TokenViewModel GenerateToken(AccountViewModel item) { TokenViewModel result = new TokenViewModel(); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(credentials); var payload = new JwtPayload { { "cus", item.UserId}, { "timestamp", DateTime.Now}, }; var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); result.Token = handler.WriteToken(secToken); result.StatusCode = 200; result.Message = "OK"; return result; } public AccountViewModel ValidToken(string token) { AccountViewModel result = new AccountViewModel(); int userId = 0; string timeStamp = string.Empty; var handler = new JwtSecurityTokenHandler(); var tokenS = handler.ReadToken(token) as JwtSecurityToken; foreach (var items in tokenS.Claims) { if (items.Type == "cus") int.TryParse(items.Value, out userId); if (items.Type == "timestamp") timeStamp = items.Value; } if (IsTimeValid(timeStamp)) { result = _repository.GetByUserId(userId); } return result; } private bool IsTimeValid(string timeStamp) { if (string.IsNullOrEmpty(timeStamp)) { return false; } DateTime oDate = Convert.ToDateTime(timeStamp.Replace("\\"", string.Empty)); if (oDate < DateTime.Today) { return false; } return true; } } }
namespace AndroidApi.Controllers.Api { [] public class TokenController : ApiController { private readonly ITokenRepository _repository; public TokenController(ITokenRepository repository) { _repository = repository; } [] [] public IHttpActionResult GetToken(AccountViewModel item) { try { TokenViewModel result = new TokenViewModel(); if (item == null || item.UserId == 0) return BadRequest("No user info"); result = _repository.GenerateToken(item); if (string.IsNullOrEmpty(result.Token) || result == null) return InternalServerError(); return Ok(result); } catch (Exception ex) { return InternalServerError(ex); } } [] [] public IHttpActionResult ValidToken() { try { HttpContext httpContext = HttpContext.Current; string authToken = httpContext.Request.Headers["Authorization"]; AccountViewModel result = new AccountViewModel(); if (string.IsNullOrEmpty(authToken)) return BadRequest(); result = _repository.ValidToken(authToken); if (result.StatusCode == 200) return Ok(result); else return NotFound(); } catch (Exception ex) { return InternalServerError(ex); } } } }
token = GetTokenFromSession(); if (token == null){ Logout(); NavigateToAccountActivity(); } else { String userDetailsJson = GetUserDetailsFromToken(token.getToken(), MainActivity.this); AccountViewModel userDetails = DeserializeUserDetails(userDetailsJson); if (userDetails.getStatusCode() == 200){ } else { Toast messageBox = Toast.makeText(MainActivity.this , userDetails.getMessage() , Toast.LENGTH_LONG); messageBox.show(); Logout(); NavigateToAccountActivity(); } } private AccountViewModel DeserializeUserDetails(String userDetailsJson) { AccountViewModel result = new AccountViewModel(); JSONObject jsonResult = null; try { jsonResult = new JSONObject(userDetailsJson); result.setStatusCode(jsonResult.getInt("StatusCode")); result.setMessage(jsonResult.getString("Message")); if (result.getStatusCode() == 200) { result.setUserId(jsonResult.getInt("userid")); result.setUsername(jsonResult.getString("user")); result.setEmail(jsonResult.getString("email")); result.setPassword(jsonResult.getString("password")); result.setActive(jsonResult.getBoolean("isactive")); } } catch (JSONException e) { e.printStackTrace(); } return result; } private String GetUserDetailsFromToken(String token, MainActivity activity) { String result = null; try { result = new ValidToken(activity).execute(config.getValidTokenEndPoint(), token).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return result; } private void NavigateToAccountActivity() { Intent main = new Intent(MainActivity.this, AccountActivity.class); startActivity(main); } private void Logout() { sharedpreferences = getSharedPreferences(AccountActivity.tokenSession, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.clear(); editor.commit(); } private TokenViewModel GetTokenFromSession() { TokenViewModel result = new TokenViewModel(); sharedpreferences = getSharedPreferences(AccountActivity.tokenSession, Context.MODE_PRIVATE); result.setToken(sharedpreferences.getString(AccountActivity.tokenKey.toString(), "")); if (result.getToken() == "") return null; return result; }
public class ValidToken extends AsyncTask<String, String, String> { ProgressDialog progressDialog; HttpURLConnection connection = null; BufferedReader reader = null; Activity activity; public ValidToken(Activity activity) { this.activity = activity; } protected void onPreExecute() { super.onPreExecute(); // display a progress dialog for good user experiance progressDialog = new ProgressDialog(activity); progressDialog.setMessage("Please Wait"); progressDialog.setCancelable(false); progressDialog.show(); } protected String doInBackground(String... params) { String result = null; TokenViewModel token; Gson gson; try { URL url = new URL(params[0]); String authToken = params[1]; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", authToken); connection.connect(); int statusCode = connection.getResponseCode(); if (statusCode == 200) { InputStream stream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } String jsonObjectHome = buffer.toString(); result = jsonObjectHome; } if (statusCode == 400){ token = new TokenViewModel(); token.setStatusCode(statusCode); token.setMessage("fail please login again"); gson = new Gson(); result = gson.toJson(token); } if (statusCode == 404){ token = new TokenViewModel(); token.setStatusCode(statusCode); token.setMessage("fail please login again"); gson = new Gson(); result = gson.toJson(token); } if (statusCode == 500){ token = new TokenViewModel(); token.setStatusCode(statusCode); token.setMessage("fail please login again"); gson = new Gson(); result = gson.toJson(token); } } catch (Exception e) { Log.e("MainActivity", e.getMessage(), e); } finally { if (connection != null) { connection.disconnect(); } try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } protected void onPostExecute(String result) { super.onPostExecute(result); progressDialog.cancel(); } }