NancyFx 2.0的开源框架的使用-Stateless(二)

继续上一篇Stateless的博文,在上一篇的博文的基础上稍微加点东西

接下来右键解决方案添加新项目,一样建一个空的Web项目

 

 

然后在StatelessDemoWeb项目里面添加Views文件夹,Scripts文件夹,并在Views文件夹里面添加index,login,secure三个页面

在index页面添加如下代码

<body>
    <div id="loggedIn" style="display:none;"><p>欢迎<span id="username">.</span><a href="#" id="logout">登出</a></p></div>
    <h1>非安全页面</h1>
    <p><a href="secure.html">安全页面</a></p>
    <script type="text/javascript">
        $(document).ready(function () {
            var apiToken = ApiToken.Get();
            if (apiToken.IsValid) {
                $("#loggedIn").show();
                $("#username").html(apiToken.Username);
                $("#logout").click(function () {
                    var request = { apiKey: apiToken.Key };
                    var success = function () {
                        ApiToken.Delete();
                        window.location = "index.html";
                    };
                    $.ajax({
                        type: 'DELETE',
                        url: api.auth,
                        data: request,
                        success: sucess,
                        dataType: "json"
                    });
                });
            }
        });
    </script>
</body>

在login页面添加如下代码

<body>
    <div>
        <input type="text" id="Username" placeholder="登陆名"/><br />
        <input type="password" id="Password" placeholder="密码"/><br />
        <input id="RememberMe" type="checkbox" value="True"/><br />
        <button id="submitButton">登陆</button>
    </div>
    <div id="errorBox" style="display:none">
        无效的用户名和密码
        <script type="text/javascript">
            $(document).ready(function () {
                $("#submitButton").click(function () {
                    $("#errorBox").hide();
                    var authRequest = {
                        username: $("#Username").val(),
                        password: $("#Password").val(),
                        rememberMe: $("RememberMe").val()
                    };
                    var success = function (response) {
                        ApiToken.Set(authRequest.username, response.ApiKey, authRequest.rememberMe);
                        window.location = "index.html";
                    };
                    var error = function () {
                        $("#errorBox").show();
                    };
                    $.ajax({
                        type: 'POST',
                        url: api.auth,
                        data: authRequest,
                        success: success,
                        error: error,
                        dataType: "json"
                    });
                });
            });
        </script>
    </div>
</body>

在secure页面添加如下代码

<body style="display:none">
    <div>
        <a href="index.html">&lt;&lt;主页</a>
        <div id="loggedIn" style="display:none">
            <p>欢迎<span id="username"></span>.<a href="#" id="logout">登出</a></p>
        </div>
        <h1>安全页面</h1>
        <div>安全内容:<span id="secureContent" class="secure"></span></div>
        <div>
            <input type="text" id="newusername" placeholder="用户名"/><br />
            <input id="newpassword" type="password" placeholder="密码"/><br />
            <input type="button" onclick="createUser()"/>
            <div id="createuserresult"></div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
            //如果 apiKey 存在, 则表示用户已登录
            //检查 apiKey 是否存在
            var apiToken = ApiToken.Get();
            if (apiToken.IsValid) {
                //用户已登录
                //获取和显示安全内容
                //使用我们存储在 cookie 中的 apiKey
                var request = { apiKey: apiToken.Key };
                //成功视图
                var success = function (response) {
                    $("#username").html(apiToken.Username);
                    $("#secureContent").html(response.SecureContent);
                    $("body").show();
                };
                //将用户重定向到401上的登录页
                var error = function (response) {
                    if (response.status == 401) {
                        window.location = "login.html";
                        return;
                    }
                    alert("出问题了" + response.error);
                };
                $.ajax({
                    url: api.secure,
                    data: request,
                    success: success,
                    error: error,
                    dataType:"json"
                });
            }
            else {
                //如果没有保存 apiToken, 则表示用户尚未登录
                //将 "em 打包" 发送到登录页
                window.location = "login.html";
            }
            if (apiToken.IsValid) {
                $("#loggedIn").show();
                $("#username").html(apiToken.Username);
                $("#logout").click(function () {
                    //将 apiKey 发送到要销毁的 api
                    var request = { apiKey: apiToken.Key };
                    //当契约在服务器上完成时,
                    //删除客户端中的 cookie, 然后重定向到主页。
                    var success = function () {
                        apiToken.Delete();
                        window.location = "index.html";
                    };
                    $.ajax({
                        type: 'DELETE',
                        url: api.auth,
                        data: resquest,
                        dataType: "json"
                    });
                });
            }
        });
        function createUser() {
            var apiToken = ApiToken.Get();
            if (apiToken.IsValid) {
                //用户已登录
                var request = {
                    username: $("#newusername").val(),
                    password: $("#newpassword").val()
                };
                //成功视图
                var success = function (response) {
                    $("#createuserresult").html("用户" + response.username + "已创建");
                };
                //将用户重定向到401上的登录页
                var error = function (response) {
                    if (response.status == 401) {
                        window.location = "login.html";
                        return;
                    }
                    alert("出问题了" + response.error);
                };
                $.ajax({
                    type: "POST",
                    url: api.create_user + "?ApiKey=" + apiToken.Key,
                    data: request,
                    success: success,
                    error: error,
                    dataType:"json"
                });
            }
            else {
                //如果没有保存 apiToken, 则表示用户尚未登录
                //将 "em 打包" 发送到登录页
                window.location = "login.html";
            }
        }
    </script>
</body>

然后在script文件夹添加api.js,apiToken.js两个文件,然后修改api.js文件如下

var api = {
    auth: "http://localhost:9611/restApi/auth",
    secure: "http://localhost:9611/restApi/secure",
    create_user:"http://localhost:9611/resApi/secure/create_user"
};

apiToken.js文件添加如下代码

var apiKeyKey = "sample_apiKey";
var usernameKey = "sample_username";

var ApiToken = {
    Set: function (username, apiKey, rememberMe) {
        var days = rememberMe ? 10 : 0;
        createCookie(apiKeyKey, apiKey, days);
        createCookie(usernameKey,username,days);
    },
    Get: function ()
    {
        var key = readCookie(apiKeyKey);
        var username = readCookie(usernameKey);
        var token = { Key: key, Username: username, IsValid: key != null };
        return token;
    },
    Delete: function ()
    {
        eraseCookie(apiKeyKey);
        eraseCookie(usernameKey);
    }
};
function createCookie(name,value,days)
{
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 1000));
        var expires = ";expires=" + date.toGMTString();
    } else {
        var expires = "";
        document.cookie = name + "=" + value + expires + ";path=/";
        console.log(document.cookie);
    }
}
function readCookie(name) {
    var cookieValue = null;
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = cap[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            var found = c.substring(nameEQ.length, c.length);
            cookieValue = found;
        }
    }
    return cookieValue;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}

运行如下

谢谢观赏

 

posted @ 2017-05-14 23:52  Lexan  阅读(678)  评论(3编辑  收藏  举报