General community landing component technology sharing (open source) Part II: OAuth download the source code and the principles of interpretation

On the section:

1: General community landing component technology sharing (open source) Part I: OAuth authorization landing introduction

2: General community landing component technology sharing (open source) novella: OAuth landing assembly processes and component integration method

 

In this section:

1: Description of the process and component design ideas and some key source explained

2: Source download

3: extension mechanism Description 

With source code Screenshot: When so will see the following ideas, you can see the shining:

 

A: Description of the process and component design ideas

 

1: Why think inflicted components?

When duplicate code or similar event> = 2, I will think about whether there might 3rd, 4th similar, if any, will be unified processing, component is the design of a number of common again.

 

2: design principle components? 

2.1: Let users the easiest way to use or calling component, to minimize the amount of code to write;

2.2: All designs are referred to under 2.1 points.

 

3: Simple component design ideas Process I: (5 lines of code design ideas)

3.1: user's operation UI design:

 

 

The above chart shows how a third party authorized landing?

He wrote in the html directly Dead? Feeling not to force, and if a few more third-party extended landing, but also to a combination of URL is a hassle.

So I think there should be UI classes, there should be a GetHtml (), to resolve to make this call easier.

 

Achieve UI.GetHtml () method:
Here is a little knowledge, in order to make the code of brevity, I spent a lot of time to think, through a combination of good coding design, reduce the amount of code written.

 

So, I used a common method to optimize this design:

         public  static  string GetHtml()
        {
             string link =  " <a href=\"{0}\" target=\"_blank\"><img src=\"{1}\" /></a> ";
            StringBuilder sb =  new StringBuilder();
             foreach (KeyValuePair< string,OAuth2Base> ob  in OAuth2Factory.ServerList)
            {
                 if (! string.IsNullOrEmpty(ob.Value.AppKey))
                {
                    sb.AppendFormat(link,  string.Format(ob.Value.OAuthUrl, ob.Value.AppKey,System.Web.HttpUtility.UrlEncode(ob.Value.CallbackUrl), ob.Key), ob.Value.ImgUrl);
                }
            }
             return sb.ToString();

         } 

This code contains several optimization ideas:

1: There should be a way you can get all current types of licenses:  OAuth2Factory.ServerList .

2: Authorization should include some type of configuration items, can read:  ob.Value.OAuthUrl, ob.Value.AppKey, ob.Value.ImgUrl

 

When figured this way, the design has not yet begun OAuth2 authorization related classes, it was just pseudo-code, with the OAuth2 class is perfect, the code here is simple molding of.

 

OK, let's look back:

3.2: OAuth authorization class design (abstract + Factory legend):

Multi-database support and database design ideas such as the one fold.

 

1: There should be a base class: OAuth2Base (including general methods and properties)

2: Continue the base class OAuth2Base, implement different authorization: SinaWeiboOAuth, QQAuth, other ... and so on!

3: There is a factory OAuth2Factory to return the current license type (as the database component to the current design is what type of database operations)

4: There is a small utility class Tool, put a small way a few commonly used.

 

In OAuth2Factory, we pre-registered authorized by all subclasses, to aggregate all type of authorization.

So GetHtml where you can get all type of authorization to traverse assembly.

Code:

         static  the Dictionary < String , OAuth2Base> _ServerList;
         /// <the Summary> ///  Gets all types (OAuth2 newly developed need to register to add it here) /// </ the Summary> Internal static  the Dictionary < String , OAuth2Base> ServerList         { GET             { IF  (_ServerList ==  null )                 {                     _ServerList =  new new  the Dictionary < String , OAuth2Base> (StringComparer.OrdinalIgnoreCase);  
        

        
 
          

            

                


                    _ServerList.Add(OAuthServer.SinaWeiBo.ToString(),  new SinaWeiBoOAuth()); // 新浪微博
                    _ServerList.Add(OAuthServer.QQ.ToString(),  new QQOAuth()); // QQ微博
                }
                 return _ServerList;
            }

} 


The overall design is not complicated, as long as to achieve, you can achieve authorization, and get third-party token and openid data.

 

Here, we did not achieve the binding account, so I started to think:

3.3 OAuth2  binding site to achieve third-party account login:

And how to achieve their own account site binding?

In the original site's database, add fields? Or create a new table, and then design?

Taking into account such a design, and site code combined with a deep degree inevitable, impossible to achieve universal, but different sites, using a different database, how many different scripts that get written?

So after thinking it over, the external data stored in an external text, taking into account the CYQ.Data V5 has been close to perfect text database support and CodeFirst operation, so refer to it as the default external database operations.

 

Of course, you get the source, if the outer block of memory need to be adjusted over a frame or other, the self-operated, non-intervention. 

 

Built-in text database solution:

如果对比上面的源码截图,你应该发现,所以类都提到了,只剩下最后一个:OAuth2Account ,它就是实现和网站绑定的罪人。

代码也很简单的说(除了继承自OrmBase和构造函数指定了表名和文本存储路径,基本上就是一个常见的实体类了):

public  class OAuth2Account:CYQ.Data.Orm.OrmBase
    {
         public OAuth2Account()
        {
             base.SetInit( this" OAuth2Account "" Txt Path={0}App_Data ");
        }
         private  int _ID;

         public  int ID
        {
             get
            {
                 return _ID;
            }
             set
            {
                _ID = value;
            }
        }
         private  string _OAuthServer;
         ///   <summary>
        
///  授权的服务类型
        
///   </summary>
         public  string OAuthServer
        {
             get
            {
                 return _OAuthServer;
            }
             set
            {
                _OAuthServer = value;
            }
        }
         private  string _Token;
         ///   <summary>
        
///  保存的Token
        
///   </summary>
         public  string Token
        {
             get
            {
                 return _Token;
            }
             set
            {
                _Token = value;
            }
        }
         private  string _OpenID;
         ///   <summary>
        
///  保存对应的ID
        
///   </summary>
         public  string OpenID
        {
             get
            {
                 return _OpenID;
            }
             set
            {
                _OpenID = value;
            }
        }
         private  string _BindAccount;
        
         private DateTime _ExpireTime;
         ///   <summary>
        
///  过期时间
        
///   </summary>
         public DateTime ExpireTime
        {
             get
            {
                 return _ExpireTime;
            }
             set
            {
                _ExpireTime = value;
            }
        }

         private  string _NickName;
         ///   <summary>
        
///  返回的第三方昵称
        
///   </summary>
         public  string NickName
        {
             get
            {
                 return _NickName;
            }
             set
            {
                _NickName = value;
            }
        }
         private  string _HeadUrl;
         ///   <summary>
        
///  返回的第三方账号对应的头像地址。
        
///   </summary>
         public  string HeadUrl
        {
             get
            {
                 return _HeadUrl;
            }
             set
            {
                _HeadUrl = value;
            }
        }


         ///   <summary>
        
///  绑定的账号
        
///   </summary>
         public  string BindAccount
        {
             get
            {
                 return _BindAccount;
            }
             set
            {
                _BindAccount = value;
            }
        }

在OAuth2Base基类里有两个和内置文本数据库打交首的函数:GetBindAccount和SetBindAccount:

         ///  添加绑定账号
        
///   </summary>
        
///   <param name="bindAccount"></param>
        
///   <returns></returns>
         public  bool SetBindAccount( string bindAccount)
        {
             bool result =  false;
             if (! string.IsNullOrEmpty(openID) && ! string.IsNullOrEmpty(token) && ! string.IsNullOrEmpty(bindAccount))
            {
                 using (OAuth2Account oa =  new OAuth2Account())
                {
                     if (!oa.Exists( string.Format( " OAuthServer='{0}' and OpenID='{1}' ", server, openID)))
                    {
                        oa.OAuthServer = server.ToString();
                        oa.Token = token;
                        oa.OpenID = openID;
                        oa.ExpireTime = expiresTime;
                        oa.BindAccount = bindAccount;
                        oa.NickName = nickName;
                        oa.HeadUrl = headUrl;
                        result = oa.Insert(CYQ.Data.InsertOp.None);
                    }
                }
            }
             return result;
        }

由于是CodeFirst及设计的是文本数据库,所以不用去兼容不同网站的数据库,自动生成文本数据库外置,只需要好好玩这个实体就可以了。

简单的就介绍到这了,设计并不复杂,代码量并不多,方法和成员也很少。

 

二:源码下载

 

源码点击下载:  OAuth2_Source.rar(download times)

 

三:扩展机制说明 

 

看完本文,下完源码,也许您可能会有以下功能需要进行调整,这里给出指导与说明:

1:界面UI的调整,具体看UI类,改动下即可。

2:增加授权种类:继承OAuth2Base,参考已有的新浪微博和QQ进行操作,当然也可以联系我让我添加。

3:如何取得绑定后的表数据:只要调用new  OAuth2Account().Select().Bind(列表);

4:更换授权存储介质,有两种方式:

 

a:保留CYQ.Data V5版本,更换数据库,只需要修改OAuth2Account类的构造函数的数据库链接更换为您现在使用的数据库链接即可。

CYQ.Data V5版本目前仅支持以下数据库(mssql、mysql、oracle、aceess、sqlite、txt、xml),前三种需要授权使用,后四种免费使用。

b:移除CYQ.Data V5版本,更换底层组件,您只要重写OAuth2Base中的 SetBindAccount和GetBindAccount两个方法即可,然后自己另外存储数据介质。

 

 

Either way, for a little experience in the development of new veterans, are relatively simple.


51cto contest entry page, thanks to passing friends easily throw a vote: http://blog.51cto.com/contest2012/2127378  

 

Reproduced in: https: //my.oschina.net/secyaher/blog/274382

Guess you like

Origin blog.csdn.net/weixin_34082789/article/details/91967109