duandi8852752 2019-03-05 21:27
浏览 76

注册数据未发送到mySQL数据库

I'm trying to create a secure login with android but I have no way of testing it's functionality as the registration feature doesn't work. I have ensured I'm properly connected to the DB and I currently do not receive any errors.

functions.php

This file contains functions for checking whether the user exists not, functions for generating password salt and hashes. I made use of random salt generator so that a unique salt and hash is generated for each user.

<?php
$random_salt_length = 32;

function userExists($username){
    $query = "SELECT username FROM member WHERE username = ?";
    global $con;
    if($stmt = $con->prepare($query)){
        $stmt->bind_param("s",$username);
        $stmt->execute();
        $stmt->store_result();
        $stmt->fetch();
        if($stmt->num_rows == 1){
            $stmt->close();
            return true;
        }
        $stmt->close();
    }

    return false;
}

function getSalt(){
    global $random_salt_length;
    return bin2hex(openssl_random_pseudo_bytes($random_salt_length));
}

function concatPasswordWithSalt($password,$salt){
    global $random_salt_length;
    if($random_salt_length % 2 == 0){
        $mid = $random_salt_length / 2;
    }
    else{
        $mid = ($random_salt_length - 1) / 2;
    }

    return
    substr($salt,0,$mid - 1).$password.substr($salt,$mid,$random_salt_length - 1);

}
?>

register.php

<?php
$response = array();
include 'db/db_connect.php';
include 'functions.php';

//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array

//Check for Mandatory parameters
if(isset($input['username']) && isset($input['password']) && isset($input['full_name'])){
    $username = $input['username'];
    $password = $input['password'];
    $fullName = $input['full_name'];

    //Check if user already exist
    if(!userExists($username)){

        //Get a unique Salt
        $salt         = getSalt();

        //Generate a unique password Hash
        $passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT);

        //Query to register new user
        $insertQuery  = "INSERT INTO member(username, full_name, password_hash, salt) VALUES (?,?,?,?)";
        if($stmt = $con->prepare($insertQuery)){
            $stmt->bind_param("ssss",$username,$fullName,$passwordHash,$salt);
            $stmt->execute();
            $response["status"] = 0;
            $response["message"] = "User created";
            $stmt->close();
        }
    }
    else{
        $response["status"] = 1;
        $response["message"] = "User exists";
    }
}
else{
    $response["status"] = 2;
    $response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>

registerActivity

public class RegisterActivity extends AppCompatActivity {
private static final String KEY_STATUS = "status";
private static final String KEY_MESSAGE = "message";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_EMPTY = "";
private EditText etUsername;
private EditText etPassword;
private EditText etConfirmPassword;
private EditText etFullName;
private String username;
private String password;
private String confirmPassword;
private String fullName;
private ProgressDialog pDialog;
private String register_url = "http://10.0.0.1/members/register.php";
private SessionHandler session;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    session = new SessionHandler(getApplicationContext());
    setContentView(R.layout.activity_register);

    etUsername = findViewById(R.id.etUsername);
    etPassword = findViewById(R.id.etPassword);
    etConfirmPassword = findViewById(R.id.etConfirmPassword);
    etFullName = findViewById(R.id.etFullName);

    Button login = findViewById(R.id.btnRegisterLogin);
    Button register = findViewById(R.id.btnRegister);

    //Launch Login screen when Login Button is clicked
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Retrieve the data entered in the edit texts
            username = etUsername.getText().toString().toLowerCase().trim();
            password = etPassword.getText().toString().trim();
            confirmPassword = etConfirmPassword.getText().toString().trim();
            fullName = etFullName.getText().toString().trim();
            if (validateInputs()) {
                registerUser();
            }

        }
    });

}

// Display Progress bar while registering
private void displayLoader() {
    pDialog = new ProgressDialog(RegisterActivity.this);
    pDialog.setMessage("Signing Up.. Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();

}

// Launch Dashboard Activity on Successful Sign Up
private void loadDashboard() {
    Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
    startActivity(i);
    finish();

}

private void registerUser() {
    displayLoader();
    JSONObject request = new JSONObject();
    try {
        //Populate the request parameters
        request.put(KEY_USERNAME, username);
        request.put(KEY_PASSWORD, password);
        request.put(KEY_FULL_NAME, fullName);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    JsonObjectRequest jsArrayRequest = new JsonObjectRequest
            (Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    pDialog.dismiss();
                    try {
                        //Check if user got registered successfully
                        if (response.getInt(KEY_STATUS) == 0) {
                            //Set the user session
                            session.loginUser(username,fullName);
                            loadDashboard();

                        }else if(response.getInt(KEY_STATUS) == 1){
                            //Display error message if username is already existing
                            etUsername.setError("Username already taken!");
                            etUsername.requestFocus();

                        }else{
                            Toast.makeText(getApplicationContext(),
                                    response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    pDialog.dismiss();
                    //Display error message whenever an error occurs
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_SHORT).show();

                }
            });

    // Access the RequestQueue through your singleton class.
    VolleySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}

sessionHandler

public class SessionHandler {
    private static final String PREF_NAME = "UserSession";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_EXPIRES = "expires";
    private static final String KEY_FULL_NAME = "full_name";
    private static final String KEY_EMPTY = "";
    private Context mContext;
    private SharedPreferences.Editor mEditor;
    private SharedPreferences mPreferences;

    public SessionHandler(Context mContext) {
        this.mContext = mContext;
        mPreferences = mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        this.mEditor = mPreferences.edit();
    }

    public void loginUser(String username, String fullName) {
        mEditor.putString(KEY_USERNAME, username);
        mEditor.putString(KEY_FULL_NAME, fullName);
        Date date = new Date();

        //Set user session for next 7 days
        long millis = date.getTime() + (7 * 24 * 60 * 60 * 1000);
        mEditor.putLong(KEY_EXPIRES, millis);
        mEditor.commit();
    }

    public boolean isLoggedIn() {
        Date currentDate = new Date();

        long millis = mPreferences.getLong(KEY_EXPIRES, 0);

        /* If shared preferences does not have a value
         then user is not logged in
         */
        if (millis == 0) {
            return false;
        }
        Date expiryDate = new Date(millis);

        /* Check if session is expired by comparing
        current date and Session expiry date
        */
        return currentDate.before(expiryDate);
    }

    public User getUserDetails() {
        //Check if user is logged in first
        if (!isLoggedIn()) {
            return null;
        }
        User user = new User();
        user.setUsername(mPreferences.getString(KEY_USERNAME, KEY_EMPTY));
        user.setFullName(mPreferences.getString(KEY_FULL_NAME, KEY_EMPTY));
        user.setSessionExpiryDate(new Date(mPreferences.getLong(KEY_EXPIRES, 0)));

        return user;
    }

    /**
     * Logs out user by clearing the session
     */
    public void logoutUser(){
        mEditor.clear();
        mEditor.commit();
    }  
}

Can you please push me in the right direction as I can't quite figure out where I'm going wrong

  • 写回答

1条回答 默认 最新

  • dongmei2351 2019-03-06 19:36
    关注

    If no error message is displayed but nothing is written to the database, it's possible your query is failing to execute.

    This piece of code in register.php currently does not have any error checking:

    //Query to register new user
    $insertQuery  = "INSERT INTO member(username, full_name, password_hash, salt) VALUES (?,?,?,?)";
    if($stmt = $con->prepare($insertQuery)){
        $stmt->bind_param("ssss",$username,$fullName,$passwordHash,$salt);
        $stmt->execute();
        $response["status"] = 0;
        $response["message"] = "User created";
        $stmt->close();
    }
    

    This can fail in two places:

    • $con->prepare() can fail if the database already knows the query won't be executed, e.g. due to a syntax error or because a table or column name doesn't exist or your user doesn't have the right permissions to perform an INSERT query into that table
    • $stmt->execute() can fail if the query fails at runtime, e.g. if you're trying to insert a string into a column that only accepts integer values.

    You should add some extra checks on that. At some point you will want to provide a useful error message to your app so users aren't confronted with technical mumbo-jumbo that they can't fix, but for now while debugging I'd recommend to dump the error message in there (it looks like a status of > 1 indicates an error, correct me if I'm wrong):

    //Query to register new user
    $insertQuery  = "INSERT INTO member(username, full_name, password_hash, salt) VALUES (?,?,?,?)";
    if($stmt = $con->prepare($insertQuery)){
        $stmt->bind_param("ssss",$username,$fullName,$passwordHash,$salt);
    
        if ($stmt->execute()) {
            $response["status"] = 0;
            $response["message"] = "User created";
        } else {
            $response["status"] = 2;
            $response["message"] = $stmt->error;
        }
    
        $stmt->close();
    } else {
        $response["status"] = 2;
        $response["message"] = $con->error;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看