Java 根据用户的类型重定向用户
我试图建立一个登录页面,其中有3种类型的用户:学生,职员,管理员,一旦他们登录,他们会被重定向到他们的具体活动。用户将存储在数据库中的一个字段中,该字段称为用户类型。我需要添加什么才能使此工作正常 Login.phpJava 根据用户的类型重定向用户,java,php,android,Java,Php,Android,我试图建立一个登录页面,其中有3种类型的用户:学生,职员,管理员,一旦他们登录,他们会被重定向到他们的具体活动。用户将存储在数据库中的一个字段中,该字段称为用户类型。我需要添加什么才能使此工作正常 Login.php <?php require_once 'include/DB_Functions.php'; $db = new DB_Functions(); $response = array("error" => FALSE); if (isset($_POST['em
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters email or password is missing!";
echo json_encode($response);
}
?>
DB_Functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// conectare BD
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // incriptare parola
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
$result = $stmt->execute();
$stmt->close();
// verifica stocarea cu succes
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
// verifica parola
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
if ($encrypted_password == $hash) {
// informatiile scrise sunt corecte
return $user;
}
} else {
return NULL;
}
}
/**
* Verifica daca user exista
*/
public function isUserExisted($email) {
$stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user exista
$stmt->close();
return true;
} else {
// user nu exista
$stmt->close();
return false;
}
}
/**
* Incriptare parola
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decriptare parola
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
LoginActivity.java
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
公共类LoginActivity扩展活动{
私有静态最终字符串标记=RegisterActivity.class.getSimpleName();
私人按钮;
私人按钮btnLinkToRegister;
私人编辑文本输入电子邮件;
私有编辑文本输入密码;
私人对话;
私人会话管理器会话;
私有SQLiteHandler数据库;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u登录);
inputEmail=(EditText)findViewById(R.id.email);
inputPassword=(EditText)findViewById(R.id.password);
btnLogin=(按钮)findViewById(R.id.btnLogin);
btnLinkToRegister=(按钮)findViewById(R.id.btnLinkToRegister屏幕);
//进度对话框
pDialog=新建进度对话框(此对话框);
pDialog.setCancelable(假);
//SQLite数据库处理程序
db=新的SQLiteHandler(getApplicationContext());
//会话管理器
session=newsessionmanager(getApplicationContext());
//检查用户是否已登录
if(session.isLoggedIn()){
//用户已登录。请将其带到主活动
意向意向=新意向(LoginActivity.this、MainActivity.class);
星触觉(意向);
完成();
}
//登录按钮点击事件
btnLogin.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图){
字符串email=inputEmail.getText().toString().trim();
字符串密码=inputPassword.getText().toString().trim();
//检查表单中是否有空数据
如果(!email.isEmpty()&&!password.isEmpty()){
//登录用户
检查登录(电子邮件、密码);
}否则{
//提示用户输入凭据
Toast.makeText(getApplicationContext(),
“请输入凭据!”,Toast.LENGTH\u LONG)
.show();
}
}
});
//链接到注册屏幕
btnLinkToRegister.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图){
意图i=新意图(getApplicationContext(),
RegisterActivity.class);
星触觉(i);
完成();
}
});
}
/**
*函数验证mysql数据库中的登录详细信息
* */
私有void checkLogin(最终字符串电子邮件、最终字符串密码){
//用于取消请求的标记
String tag\u String\u req=“req\u login”;
设置消息(“登录…”);
showDialog();
StringRequest strReq=新的StringRequest(Method.POST,
AppConfig.URL\u登录,新建响应.Listener(){
@凌驾
公共void onResponse(字符串响应){
Log.d(标记“登录响应:+Response.toString());
hideDialog();
试一试{
JSONObject jObj=新的JSONObject(响应);
布尔错误=jObj.getBoolean(“错误”);
//检查json中的错误节点
如果(!错误){
//用户已成功登录
//创建登录会话
session.setLogin(true);
//现在将用户存储在SQLite中
stringuid=jObj.getString(“uid”);
JSONObject user=jObj.getJSONObject(“用户”);
字符串名称=user.getString(“名称”);
String email=user.getString(“电子邮件”);
在=用户处创建的字符串
.getString(“创建于”);
//在用户表中插入行
db.addUser(姓名、电子邮件、uid、创建地址);
//开展主要活动
意向意向=新意向(LoginActivity.this,
主要活动(课堂);
星触觉(意向);
完成();
}否则{
//登录时出错。获取错误消息
String errorMsg=jObj.getString(“error_msg”);
Toast.makeText(getApplicationContext(),
errorMsg,Toast.LENGTH_LONG).show();
}
}捕获(JSONException e){
//JSON错误
e、 printStackTrace();
Toast.makeText(getApplicationContext(),“Json错误:+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(标记“登录错误:+Error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(),Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@凌驾
受保护的映射getParams(){
//将参数发布到登录url
Map params=新的HashMap();
参数put(“电子邮件”,电子邮件);
参数put(“密码”,密码);
返回参数;
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
intent.putExtra("usertype", userType);
int userType = getIntent().getIntExtra("usertype", -1);//-1 is the default. If you use -1 for something, change it to any other number